I am learning about global exception handling in spring boot. I have a designed a controller annotated with @RestController which has a controller method that throws an exception. I have designed another class named GlobalExceptionHandling annotated with @RestControllerAdvice/@ControllerAdvice. It works fine and handles the exception when annotated with @RestControllerAdvice but doesn't work as expected when annotated with @ControllerAdvice. I am sharing my code and the responses i got on postman.
DemoController:
@RestController
public class DemoController {
@RequestMapping("exception/arithmetic")
public String controllerForArithmeticException()
{
throw new ArithmeticException("Divide by zero error");
}
@RequestMapping("exception")
public String controllerForException() throws Exception
{
throw new Exception("An exception occurred");
}
}
GlobalExceptionHandler: (with @RestControllerAdvice)
@RestControllerAdvice
public class GlobalExceptionHandler{
@ExceptionHandler(value = Exception.class)
public String handleException(Exception e)
{
return "Exception: " + e.getMessage();
}
@ExceptionHandler(value = ArithmeticException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public String handleArithmeticException(ArithmeticException e)
{
return "ArithmeticException: " + e.getMessage();
}
}
Response on postman:
Status: 404 Bad Request
Response Body: ArithmeticException: Divide by zero error
Console: Nothing gets printed on console.
GlobalExceptionHandler: (with @ControllerAdvice)
@ControllerAdvice
public class GlobalExceptionHandler{
@ExceptionHandler(value = Exception.class)
public String handleException(Exception e)
{
return "Exception: " + e.getMessage();
}
@ExceptionHandler(value = ArithmeticException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public String handleArithmeticException(ArithmeticException e)
{
return "ArithmeticException: " + e.getMessage();
}
}
Response on postman:
Status: 404 Bad Request
Response Body: {
"timestamp": "2020-02-15T12:41:40.988+0000",
"status": 404,
"error": "Not Found",
"message": "Divide by zero error",
"path": "/exception/arithmetic"
}
Console: Nothing gets printed on console.
Can you explain what exactly @ResponseBody do?