Sara Selim
Sara Selim

Reputation: 457

handle Http Request in exception case

I have an application the backend is spring MVC and the front end is angular.the server side sends data to the client side. My question is if something wrong happens in the server side what is the best way to handle it. I think about 2 solutions : the first one is to create new model which contains 3 attributes like this

public class Response{ boolean hasError; Object data; Exception ex}

and send this object to the client side then in the client side check if the hasError equals false check the data object otherwise check the exception object. this solution grants that in all case the http response status will be 200 from the server side,

the second solution is to create custom status code for the http response then in the front end use this status code to detect exception type.

The question is what is the best practice of these 2 solutions ? Or is there is a solution better than these 2 solutions ?

Upvotes: 0

Views: 578

Answers (2)

Nelson Christos
Nelson Christos

Reputation: 67

If you are using micro services based architecture, why not give the Netflix hystrix fault tolerance lib a try. It uses the circuit breaker pattern and allows the microservice to operate when a related service fails.

Upvotes: 1

Urosh T.
Urosh T.

Reputation: 3814

TL; DR:

Use what you have out of the box with Spring and do it by REST principles. Handle the error on the frontend with more generic messages so that there is no need for a custom model when it comes to error handling, just http status codes.

Longer version:

There is no need to reinvent the wheel and write custom http codes. There are plenty around and Spring has an excellent support for handling exceptions with @ControllerAdvice and @ExceptionHanlder annotations. Some reference and a quick guide

Depending on your backend endpoints you can write various exception classes that correspond best to what you need. Try to follow the REST principles here, you will thank yourself later on. Also, there is no need to propagate the error all the way to the front end. For example - If you had a NullPointerException happened in the backend, do not display Null pointer happened to the user on the frontend, this helps him nothing.

this solution grants that in all case the http response status will be 200 from the server side

Don't return 200 if there was an error, because that is confusing to the caller. If there was an error, return a 4xx or a 5xx code that corresponds to the error occurred and then handle that case on the frontend independently from the backend (e.g, database is down, you return an error 500 to the frontend and have it display a message to the user like Service temporarily down, please try again later or something like that).

Upvotes: 1

Related Questions