Mr bond
Mr bond

Reputation: 133

Exception Handler method not getting invoked spring boot

@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler{

@ExceptionHandler
    public final ResponseEntity<Object> handleOrgIdException(OrgIdException ex, WebRequest request){
       GeneralExceptionResponse exceptionResponse = new GeneralExceptionResponse("-1", ex.getMessage());
       return new ResponseEntity(exceptionResponse, HttpStatus.BAD_REQUEST);
    }   
}


public class OrgIdException extends RuntimeException{

   private static final long serialVersionUID = 1L;

   public OrgIdException(String message){
    super(message);
   }
}


@RestController
@Api(tags = "sample")
@RequestMapping(path = "v1", produces = { MediaType.APPLICATION_JSON_VALUE})
public class SampleEndpoint extends AbstractEndpoint {

   @GetMapping("badrequest")
   public ResponseEntity<SampleObject> doBadRequest(Principal p) throws Exception {
      throw new OrgIdException("exception thrown.....");
   }
}

Server Logs :

2020-01-27 19:16:34,708 INFO  [http-nio-8080-exec-1] [] [] [] org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-01-27 19:16:34,713 INFO  [http-nio-8080-exec-1] [] [] [] org.springframework.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-01-27 19:16:34,748 INFO  [http-nio-8080-exec-1] [] [] [] org.springframework.web.servlet.DispatcherServlet : Completed initialization in 34 ms
2020-01-27 19:16:34,893 ERROR [http-nio-8080-exec-1] [] [LOCAL] [] com.mckesson.lib.spring.controller.RestController : Failed to process the request
com.mckesson.ms.template.v1.exception.OrgIdException: exception thrown.....
    at com.mckesson.ms.template.v1.endpoint.SampleEndpoint.doBadRequest(SampleEndpoint.java:32) ~[main/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_221]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_221]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_221]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_221]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942) ~[spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005) [spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897) [spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:645) [javax.servlet-api-4.0.1.jar:4.0.1]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882) [spring-webmvc-5.1.5.RELEASE.jar:5.1.5.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:750) [javax.servlet-api-4.0.1.jar:4.0.1]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) [tomcat-embed-websocket-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [tomcat-embed-core-9.0.16.jar:9.0.16]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [tomcat-embed-core-9.0.16.jar:9.0.16]

I am using spring boot application. Can anyone please suggest, why Exception handler method is not getting called? When I add the exception handler method to my controller itself then it works fine.

Upvotes: 0

Views: 1322

Answers (2)

junlan
junlan

Reputation: 261

Can create one global exception handler to handle http exception via extent ResponseEntityExceptionHandler

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
  @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                         HttpHeaders headers,
                         HttpStatus status, 
                         WebRequest request) {
        Map<String, Object> body = new LinkedHashMap<>();
        body.put("timestamp", new Date());
        body.put("status", status.value());

        //Get all errors
        List<String> errors = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(x -> x.getDefaultMessage())
                .collect(Collectors.toList());

        body.put("errors", errors);

        return new ResponseEntity<>(body, headers, status);
    }

Upvotes: 0

Supun Wijerathne
Supun Wijerathne

Reputation: 12938

Just try with a simple class like this.

@ControllerAdvice
public class MyControllerAdvice {
    @ResponseBody
    @ExceptionHandler(OrgIdException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public GeneralExceptionResponse handlePersonNotFound(OrgIdException ex) {
        return new GeneralExceptionResponse("-1", ex.getMessage());
    }
}

Upvotes: 1

Related Questions