0

I am writing a web application using Spring Boot that frequently updates data on the back end and returns the updated object to reflect the update on the front end.

The question I have is what to return from my methods if the update should fail for some reason.

I am currently returning the object as it was received should it fail but as it stands the state on the front end would not reflect the failure on the back end in the case that it occurs.

I want to return the object to update the state but doing so prevents me from returning a String or HttpStatus indicating a problem doesn't it? Returning the old object doesn't seem a good solution either.

JoSSte
  • 2,953
  • 6
  • 34
  • 54
J-Daniel-S
  • 47
  • 8

2 Answers2

2

You can throw an exception in this case of failure from your REST controller.

To handle this exception, Spring provides ResponseEntityExceptionHandler callback class with the help of which you can handle the thrown exception and set different headers in the response entity.

So on client-side, you can recognise that some failure is occurred on server side.

You can set HttpStatus as HttpStatus.INTERNAL_SERVER_ERROR and add more details in the body.

JoSSte
  • 2,953
  • 6
  • 34
  • 54
1

The question I have is what to return from my methods if the update should fail for some reason.

You first need to determine whether the error was caused by the client or by the server, then you can determine the most suitable status code to be returned, either in the 4xx or in the 5xx range. See this answer which may give you some insights.

Instead of returning the request request back in the response, you should return a payload that describes what the problem was. Consider, for example, the payload defined in the RFC 7807 along with the application/problem+json media type.

Finally, this answer may give you insights on how to map an exception to a HTTP status code in Spring:

Community
  • 1
  • 1
cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • How can I do this and still return the updated Object if the update was successful? I want to use the response to update the state on my front end? I guess I could use Jackson to render my object into a String and return that but it seems rather redundant given that the controller sends its response in JSON anyway. – J-Daniel-S Jul 22 '20 at 09:51