Generic Exception Handling for all the resources

Generic Exception Handling for all the resources

we need custom exception structure while getting exception resonse


ErrorDetails.java: for creating your Custom Response Structure

public class ErrorDetails {

private LocalDateTime timestamp;

private String message;

private String details;

private String errorGenerator;

public ErrorDetails(LocalDateTime timestamp, String message, String details, String errorGenerator) {

super();

this.timestamp = timestamp;

this.message = message;

this.details = details;

this.errorGenerator = errorGenerator;

}

public LocalDateTime getTimestamp() {

return timestamp;

}

public String getMessage() {

return message;

}

public String getDetails() {

return details;

}

public String getErrorGenerator() {

return errorGenerator;

}

}


CustomizedResponseEntityExceptionHandler.java class is created similar formate of ResponseEntityExceptionHandler class

to achive centralized form of handling exception


@ControllerAdvice

public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(Exception.class)

public final ResponseEntity<Object> handleAllException(Exception ex, WebRequest request) throws Exception {

ErrorDetails errorDetails = new ErrorDetails(LocalDateTime.now(),

ex.getMessage(), request.getDescription(false), "Java Dev");

return new ResponseEntity<Object>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);

}

@ExceptionHandler(UserNotFoundException.class)

public final ResponseEntity<Object> handleNotFoundException(Exception ex, WebRequest request) throws Exception {

ErrorDetails errorDetails = new ErrorDetails(LocalDateTime.now(),

ex.getMessage(), request.getDescription(false), "UserNotFoundException");

return new ResponseEntity<Object>(errorDetails, HttpStatus.NOT_FOUND);

}


}



1. This will be used for handle all the exception and give response as INTERNAL_SERVER_ERROR

@ExceptionHandler(Exception.class)

public final ResponseEntity<Object> handleAllException(Exception ex, WebRequest request) throws Exception {

ErrorDetails errorDetails = new ErrorDetails(LocalDateTime.now(),

ex.getMessage(), request.getDescription(false), "Java Dev");

return new ResponseEntity<Object>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);

}

2. This will used for your custom exception class UserNotFoundException to be NOT_FOUND

@ExceptionHandler(UserNotFoundException.class)

public final ResponseEntity<Object> handleNotFoundException(Exception ex, WebRequest request) throws Exception {

ErrorDetails errorDetails = new ErrorDetails(LocalDateTime.now(),

ex.getMessage(), request.getDescription(false), "UserNotFoundException");

return new ResponseEntity<Object>(errorDetails, HttpStatus.NOT_FOUND);

}


Comments

Popular posts from this blog

Introduction of RESTful Web Service

Learn JPA and Hibernate

Implementing Dynamic Filtering for Rest API