I am using Spring Boot to handle REST calls. In this context, I have implemented a controller class with the following method:
@GetMapping("/{id}")
public ResponseEntity<employeeDetails> getEmployee(@PathVariable Long id) {
Optional<Employee> employee = employeeService.getEmployee(id);
if (employee.isPresent()) {
return ResponseEntity.ok(employee.get());
} else {
throw new ApiRequestException("Could not find requested employee");
}
}
I am now sending a request, asking for a non-existent employee. I have verified that the else-block is executed. My issue is that I am not returned a custom error message, instead I see the same old error message in my Browser console that I have seen before implementing the ApiRequestException:
I cannot understand why I don't see my custom error message. Here is how I have implemented the ApiRequestException:
I have implemented the ApiRequestException class:
public class ApiRequestException extends RuntimeException { public ApiRequestException(String message) { super(message); } }
I have implemented an Exception handler:
@ControllerAdvice public class ApiExceptionHandler { @ExceptionHandler(value = { ApiRequestException.class }) public ResponseEntity<Object> handleApiRequestException(ApiRequestException e) { HttpStatus badRequestStatus = HttpStatus.BAD_REQUEST; ApiRequestError apiRequestError = new ApiRequestError(badRequestStatus, e.getMessage()); return ResponseEntity.status(badRequestStatus).body(apiRequestError); } }
Well, as you can see, the exception handler is using an ApiRequestError class. I have implemented this as well: It's just a class that stores a message-string and an httpStatus.
When debugging my application, I have verified that the exception handler is called. Setting a breakpoint inside my GET-Controller shows that the ApiRequestException is thrown. The exception is handled by the ExceptionHandler.
So, anyways, I cannot explain why there is no custom error message in my browser console, but instead what seems to be a default message generated by Spring Boot. Can somebody help?
===================================================
update:
As it turns out, this issue seems to be related to my frontend, not my backend. The code I have presented here works fine. I have tested this by logging the error message in the way described in this follow-up question.
Try extending ResponseEntityExceptionHandler
@ControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler{
...
}
Did you add these configs in the properties file?
server.error.include-message=always
server.error.include-binding-errors=always
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.