Reputation: 184
I built a rest API using Spring Boot, that returns a custom ResponseEntity when an excpetion occurs using a class xxEntity
that I created
public class xxEntity<T> {
private T body;
private HttpStatus status;
private int statusCode;
private xxException error;
public xxEntity(T body) {
this.body = body;
status = HttpStatus.OK;
this.statusCode = status.value();
}
public xxEntity(HttpStatus status, xxException error) {
this.status = status;
this.statusCode = status.value();
this.error = error;
}
}
When there is an exception I return the entity as following:
return new xxEntity<>(HttpStatus.NOT_FOUND, new xxException(ex));
Where ex
is a json containing the String
french message, String
english message and an int
internal error code.
It returns a custom object with the following details:
{
"body": null,
"status": "NOT_FOUND",
"statusCode": 404,
"error": {
"userMessage": {
"en": "No user found",
"fr": "Pas d'utilisateur trouvé",
"errorCode": 10
}
}
}
Till there everything is working fine, the only issue is that I can return only as status code 200 OK
I actually want to return different status code according to the event that happened so that in the front-end it can be handle easily as an exception without having to write multiple if..else conditions
Example: Actually in the json that I attached the status code is 404 NOT FOUND but when making the request in postman I receive a 200 OK
Upvotes: 1
Views: 1054
Reputation: 915
if you use sprint 5 you can try:
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Foo Not Found", exc);
in your controller.
Upvotes: 0
Reputation: 756
HttpStatus codes are returned as part of your Response Object. You might need to do something like this ->
ResponseEntity.status(HttpStatus.NOT_FOUND).body();
See the open source project - response-builder that is a wrapper to construct custom api responses and exception handling -> https://github.com/AccessGateLabs/response-builder
Upvotes: 0
Reputation: 2297
The best way to do it using a controllerAdvice. This is a class annotated with @ControllerAdvice
where you define methods for every exception type you want to manage and the result of that function is the response of the api, I mean an httpstatus along with the bosy you want.
In addition to this solution you can use others like using @ExceptionHandler
in error handler methods inside the controller class. But I think the cleanest way is using a ControllerAdvice.
Anyway, here you can find examples of all the ways you can manage exceptions in spring rest APIs
https://www.baeldung.com/exception-handling-for-rest-with-spring
Upvotes: 0