Home > Blockchain >  How a custom exception handled responses message could be trimmed into shorter one for a Spring Boot
How a custom exception handled responses message could be trimmed into shorter one for a Spring Boot

Time:10-14

When I run my application, upon giving correct data in Postman, I get something like this.

{
 "sportsId":"1000",
 "noOfPlayers":"22",
 "sportsName":"Hockey",
 "sportsType":"Outdoor"
}

Response

{
 "sportsId":"1000",
 "sportsName":"Hockey",
 "sportsType":"Outdoor"
}

In case any exception is handled, like entering the same data, this would be the response of custom exception handling.

{
 "timestamp": "2022-10-13T18:44:27.911 00:00",
"status": 500,
"error": "Internal Server Error",
"trace": "com.cognizant.sportseventmanagement.exception.SportInsertionException: Sport already Exist!\r\n\tat com.cognizant.sportseventmanagement.service.SportsEventService.lambda$addSport$0(SportsEventService.java:34)\r\n\tat java.base/java.util.Optional.ifPresent(Optional.java:178)\r\n\tat com.cognizant.sportseventmanagement.service.SportsEventService.addSport(SportsEventService.java:33)\r\n\tat com.cognizant.sportseventmanagement.controller.SportsEventController.addSport(SportsEventController.java:66)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\r\n\tat java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)\r\n\tat java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\r\n\tat java.base/java.lang.reflect.Method.invoke(Method.java:568)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)\r\n\tat org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)\r\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)\r\n\tat org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067)\r\n\tat org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)\r\n\tat org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)\r\n\tat org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:681)\r\n\tat org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)\r\n\tat javax.servlet.http.HttpServlet.service(HttpServlet.java:764)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)\r\n\tat org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)\r\n\tat org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)\r\n\tat org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197)\r\n\tat org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)\r\n\tat org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)\r\n\tat org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135)\r\n\tat org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)\r\n\tat org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)\r\n\tat org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:360)\r\n\tat org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:399)\r\n\tat org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)\r\n\tat org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:890)\r\n\tat org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1787)\r\n\tat org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)\r\n\tat org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)\r\n\tat org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)\r\n\tat java.base/java.lang.Thread.run(Thread.java:833)\r\n",
"message": "Sport already Exist!",
"path": "/api/v1/sportsEvent/addSport"
}

But I want the response to be in this way

{
  "status":500,
  "message":"Sport already Exist!"
}

Could someone please help me what all changes I require to undergo so that I could simply my response?

CodePudding user response:

In your Exceptions package, add a RestResponseEntityExceptionHandler.java class which extends to ResponseEntityExceptionHandler.

Annotate the class with @ExceptionalHandler(Class_to_be_handeled.java) @ResponseBody @ResponseStatus(HttpStatus.NOT_FOUND) annotations.

Finally, create a ExceptionMessage.java class to handle the response.

Please find the below code for further clarification.

RestResponseEntityExceptionHandler.java

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends 
ResponseEntityExceptionHandler {

@ExceptionHandler(Class_to_be_handeled.class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ExceptionMessage sportInsertionExceptionHandler(SportInsertionException 
exception)
{
    ExceptionMessage message = new ExceptionMessage(HttpStatus.BAD_REQUEST, 
    exception.getMessage());

    return message;
}
}

ExceptionMessage.java

public class ExceptionMessage {

private HttpStatus httpStatus;
private String msg;

public ExceptionMessage() {
}

public ExceptionMessage(HttpStatus httpStatus, String msg) {
    this.httpStatus = httpStatus;
    this.msg = msg;
}

public HttpStatus getHttpStatus() {
    return httpStatus;
}

public void setHttpStatus(HttpStatus httpStatus) {
    this.httpStatus = httpStatus;
}

public String getMsg() {
    return msg;
}

public void setMsg(String msg) {
    this.msg = msg;
}
}

Final Response :

{
 "httpStatus": "BAD_REQUEST",
 "msg": "Sport already Exist!"
}

Hope this is helpful!

you can ping me any time.

CodePudding user response:

you could return an HttpStatus.INTERNAL_SERVER_ERROR with an message inside body, please have a look at below code.

    @RequestMapping("/insert")
    public ResponseEntity<Object> insertData(HttpServletRequest request){
        if ( checkDuplicateData(request) ) {
        throw new ServerException();
     } else{
        return new ResponseEntity.ok("Data Inserted successfully");
     } 
    }

Explanation: It will check if data is duplicate then will throw server exception otherwise required response of ok/200

@ExceptionHandler code here

@ExceptionHandler(value = DuplicateDataApiException.class)
    public ResponseEntity<Object> duplicateDataApiException(DuplicateDataApiException exception){
        return new ResponseEntity<>("Duplicate Data Error", HttpStatus.INTERNAL_SERVER_ERROR);
    }

I hope, it helps!

  • Related