0

I have many controllers like this one

@RestController
@RequestMapping("/contracts")
public class ContractsController {

    @Autowired
    ContractsService service;

    @PostMapping("/selectAll")
    public WebMessageModel selectAll(@RequestBody ContractFiltersInputModel inputModel) {
        return new WebMessageModel(true, service.selectAll(inputModel));
    }
}

And I have another controller

@Controller
public class BaseController {

    private static Logger logger = LoggerFactory.getLogger(IndexController.class);

    @RequestMapping
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {

            String requestURI = request.getRequestURI();
            StringBuffer requestURL = request.getRequestURL();
            logger.info("-----requestURI => " + requestURI + ", requestURL => " + requestURL);

            request.getRequestDispatcher(requestURI).forward(request, response);

            logger.info("-----response has been commited");

        } catch (Throwable t) {
            t.printStackTrace();
            request.getRequestDispatcher("/handleException").forward(request, response);

        }

    }
}

I need all incoming requests to go through this BaseController in order to make one global TRY-CATCH block. How can I implement that? Is this approach really good idea? Maybe there are some other awesome aproaches?

1
  • 3
    If you want to deal with exceptions consider using @ControllerAdvice Commented Sep 12, 2018 at 10:59

3 Answers 3

1

If you want to intercept every request to your controllers endpoint before it enters the controller method, you would need to implement a filter. You may go through this tutorial to understand how to implement a filter.

If you want to catch all the exceptions that result out of requests to your controller endpoints (the exception could have been thrown anywhere - controller, service, repository etc) at one place, then you should implement ExceptionHandlers within a ControllerAdvice. A simple example would be like this:

@ControllerAdvice
public class ExceptionHandlerAdvice {

@ExceptionHandler(MismatchedInputException.class)
public ResponseEntity<Void> handleMismatchedInputException(MismatchedInputException e) {
    return ResponseEntity.status(BAD_REQUEST).build();
}

@ExceptionHandler(InvalidFormatException.class)
public ResponseEntity<Void> handleInvalidFormatException(InvalidFormatException e) {
    return ResponseEntity.status(UNPROCESSABLE_ENTITY).build();
}

}

The above will make sure any exception that's specified in the exception handler will be caught here so that exception response from your REST API can be streamlined. More on the same here.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use filters to execute some logic before or after requests. In your case a global error handling would be more helpful:

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = { IllegalArgumentException.class, IllegalStateException.class })
    protected ResponseEntity<Object> handleConflict(
      RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, 
          new HttpHeaders(), HttpStatus.CONFLICT, request);
    }
}

This snippet is taken from here.

Comments

0

What you looking for is @ControllerAdvice. Here's how to use it http://blog.codeleak.pl/2013/11/controlleradvice-improvements-in-spring.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.