The following are different exception handling approaches in Java Spring MVC framework

Controller level Exception Handler

  • Controller exception can be handled by:
    – Adding @ExceptionHandler annotation
    – Implementing HandlerExceptionResolver

Global Exception Handler

  • Adding @controllerAdvice annotation to define global exceptions
  • Using HandlerExceptionResolver interface for creating global exception handlers

Custom Errors Mapping

  • Adding @ResponseStatus annotation to map custom errors to exception status code

Handling Controller Exceptions with @ExceptionHandler Annotation

  • To Implement @ExceptionHandler annotation
    – Add @exceptionHandler annotation to the method
    – Include a list of exceptions to be handled by the method
    – When handling multiple exception, specific exceptions are thrown ignoring general exceptions
    – Return error response as string, Modelview object, ResponseEntity or @Responsebody

Vulnerable Code: Unhandled Exception

Secure Code: Handling Exception using @ExceptionHandler Annotation

Handling Controller Exceptions with HandlerExceptionResolver

  • To implementing HandlerExceptionResolver Interface
    – Override the resolveException() method
    – It will handle all the exceptions of the controller
    – Use instanceof to get the exception type

Example: Controller Exception Handling using HandlerExceptionResolver