user9735824
user9735824

Reputation: 1256

Error Handling in REST API: Best Practice

I am trying to develop a rest api that basically return information about country. So my url will be something like

http://myrestservice/country/US

so when a request come with valid country, my rest service will prepare information for that country and prepare object called countryInfo and return this as

return  ResponseEntity.status(200).body(countryInfo);

now say user send request as http://myrestservice/country/XX. In this case since XX is not valid country i have send response. I read in different place and most of them only explain about status code. My question is what is the best way to return error.

  1. return ResponseEntity.status(404).body("Invalid Country");
  2. return ResponseEntity.status(404).body(myobject); //here myObject will be null.

  3. Prepare a Class say MyResponse.java as below.

    public class MyResponse {
    
      private String errorCode;
      private String errorDescription;
      private CountryInfo countryInfo 
    
    }
    

And return this object no matter if there are error or not. If there is error set errorCode and errorDescription field with proper value and set countryInfo to null and for no error set errorCode and errorDescription as empty and countryInfo with data.

Which of the above option is considered standard way to handle error.

Upvotes: 1

Views: 7722

Answers (3)

Claudia Chersin
Claudia Chersin

Reputation: 192

You can use Zalando Problem, a library that implements application/problem+json.

https://github.com/zalando/problem

https://thecodingduck.blogspot.com/2023/01/best-practices-for-rest-api-design.html#standard_error

Upvotes: -1

Cristian Colorado
Cristian Colorado

Reputation: 2040

You could use @ControllerAdvice to handle exceptions:

Your endpoint needs to identify the error and throw an error:

@RequestMapping("/country/{code}")
public ResponseEntity<Country> findCountry(String code) {
  Country country = this.countryRepository(code);
  if(country == null) throws new IllegalArgumentException("Invalid country code: " + code);
  return  ResponseEntity.status(200).body(country);
}

Then you create a class that will handle the exceptions of your endpoints:

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = { IllegalArgumentException.class })
    protected ResponseEntity<Object> handleConflict(RuntimeException ex, WebRequest request) {
        String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, 
          new HttpHeaders(), HttpStatus.CONFLICT, request);
    }
}

There you have to define the status code to indicate user what kind of error was generated, 409 in order to indicate there was a conflict.

Also, there you can define a body including further information, either a string or a custom object containing an error message and description you offer to the client thru documentation.

Upvotes: 0

Evert
Evert

Reputation: 99523

You should indeed return a 404, but what you return in the body depends on you.

Some people just return a html response with some human-readable information, but if you want your API client to get some more information about why the 404 happened, you might also want to return JSON.

Instead of using your own format, you should use the standard application/problem+json. It's a very simple format:

https://www.rfc-editor.org/rfc/rfc7807

Upvotes: 3

Related Questions