Response Entity Exception Handling
mark the class with
ControllerAdvice
andResponseStatus
The class should extend
ResponseEntityExceptionHandler
Annotate the member function with
@ExceptionHandler(T.class)
where T is the custom exception classMake sure to include
String message
andInteger statusCode
in the custom exception.Example
@ControllerAdvice
@ResponseStatus
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler
{
@ExceptionHandler(DepartmentExceptions.class)
public ResponseEntity<ErrorMessage>
departmentException(DepartmentExceptions exception)
{
Integer exceptionStatus = exception.getStatusCode();
if (exceptionStatus == 404) {
ErrorMessage message =
new ErrorMessage(HttpStatus.NOT_FOUND, exception.getMessage());
return ResponseEntity.status(HttpStatus.CREATED).body(message);
}
}
}
Last updated
Was this helpful?