Generic Exception Handling in Web-services

Creating Generic Exception class for Web-services:

Step 1. Create a Generic class that extends ResponseEntityExceptionHandler.
Step 2. Annotate the class with @RestController(as it will send Exception response to client) & @ControllerAdvice (to intercept all controller’s exception).

Method Level Changes:
Step 3. Create method(s) signature similar to one in ResponseEntityExceptionHandler to handle Specific Exception . Mark it with annotation @ExceptionHandler(Exception.class) where the parameter is type of exception it will handle.

@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handleAllException(Exception ex, WebRequest request)

{

ExceptionResponse exceptionResponse = new ExceptionResponse(new Date(), ex.getMessage(),
request.getDescription(false));
return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);

}


Step 4. methods return type is ResponseEntity with take body and status as parameter,
body is supplied form ExceptionType being thrown and status-code as per requirement(HttpStatus.CODE_NAME) .

Note : Syntax

ResponseEntity([header],[body],[status-code])

Project Reference:

Artifact – restful-web-services

Package – com.tutorial2implement.webservice.restfulwebservices.application.exception;

Note :

In earlier versions of Spring, extending ResponseEntityExceptionHandler and overriding its methods allowed developers to customize exception handling globally. However, with the release of Spring Framework 6.0, the design has evolved, and some of these methods are now final to promote a more flexible and configurable approach to exception handling.
solution - avoid extending as extends ResponseEntityExceptionHandler and use the method direcctly

Published by

Unknown's avatar

sevanand yadav

software engineer working as web developer having specialization in spring MVC with mysql,hibernate

Leave a comment