I do have a class CustomResponseEntityExceptionHandler
class extending ResponseEntityExceptionHandler
with 2 methods one for handling wrong formats and the other one when a resource (url) is requested but does not exist. I would like to give the user a custom message instead of the default White Label Error page of Spring. I'm trying to understand why my handleResourceNotFoundException
method from CustomResponseEntityExceptionHandler
is not called when a non existing URI is requested but instead I keep having the White Label Error page. Thanks for your help!
curl localhost:8080/doesnotexist
This is my CustomResponseEntityExceptionHandler
@ExceptionHandler(Exception.class)
public final ResponseEntity<ErrorDetails> handleAllWrongFormatExceptions(WrongFormatException ex,
WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(true));
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(ResourceNotFoundException.class)
public final ResponseEntity<ErrorDetails> handleResourceNotFoundException(ResourceNotFoundException ex,
WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
Simple class for holding custom error details
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
public ErrorDetails(Date timestamp, String message, String details) {
this.timestamp = timestamp;
this.message = message;
this.details = details;
}
public Date getTimestamp() {
return timestamp;
}
public String getMessage() {
return message;
}
public String getDetails() {
return details;
} }
And here is my controller
@Controller
public class StringManipController {
@Autowired
private StringProcessingService stringProcessingService;
@GetMapping("/")
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseBody
public String home(@RequestParam(name = "value", required = false, defaultValue = "") String value) {
return "Welcome to the String Processing Application";
}
@GetMapping("/stringDedup")
@ResponseBody
public ProcessedString doManip(@RequestParam(name = "value", required = false, defaultValue = "") String value) {
String result = stringProcessingService.getStringManipulation(value);
return new ProcessedString(result);
}
@GetMapping("/writeNumber")
@ResponseBody
public ProcessedString getWriteNumber(
@RequestParam(name = "value", required = false, defaultValue = "") String value) {
String number = stringProcessingService.getNumberToWords(value);
return new ProcessedString(number);
} }
And here the ResourceNotFoundException class
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
private static final long serialVersionUID = 266853955330077478L;
public ResourceNotFoundException(String exception) {
super(exception);
} }