0

I would like to know best practice on the following case(s) regarding Rest API Responses.

First code piece

@GetMapping("/person/{id}")
public ResponseEntity<Person> postPersonDetails(@PathVariable("id) Long id) {
    Person person = personService.getPersonById(id);
    if (null == person) {
       throw new ResourceNotFoundException().withMessage("PERSON_NOT_FOUND");
    }
    return new ResponseEntity<Person>(person, HttpStatus.OK);
}

Second code piece

@GetMapping("/person/{id}")
public ResponseEntity<Person> postPersonDetails(@PathVariable("id) Long id) {
    Person person = personService.getPersonById(id);
    if (null == person) {
       return new ResponseEntity<Person>(null, HttpStatus.NotFound);
    }
    return new ResponseEntity<Person>(person, HttpStatus.OK);
}

The question is

  1. Which one is better for responding error message to API consumer (user)?

  2. Throwing exception leaves error message in the log. If throwing exception is better, how should I avoid from leaving error messages which come from exceptions thrown intentionally?

Thanks

kelvinsu
  • 63
  • 5
  • Why do u want to hide error messages from log? If a person was not found which u expected to be found, that's an error, and you should log it as an error. Its considered good practice, check this post out; https://stackoverflow.com/questions/11746894/what-is-the-proper-rest-response-code-for-a-valid-request-but-an-empty-data – Teun van der Wijst Oct 09 '18 at 07:53
  • Error messages which are coming from Exception is quite long. Real and uncontrollable exceptions are okay to leave with long stacks. But this person exception is able to handle and would like to log as short and readable error message. – kelvinsu Oct 09 '18 at 08:07

1 Answers1

0

I would consider a modified approach from your first example: You throw a PersonNotFoundException and add an exception handler that convers that specific exception to the HTTP 404 and appropriate error message in the payload.

For example:

@ExceptionHandler(PersonNotFoundException.class)
public ResponseEntity<Void> personNotFound()
{
    return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}

This keeps your mapping code from the exception to the response separate and reusable.

Thomas
  • 11,272
  • 2
  • 24
  • 40