user2428795
user2428795

Reputation: 547

How do I add errors to my Spring MVC REST Service?

How can I change/update the following REST call from Spring MVC to return a error if the user did not enter of the the two names I was coding for.. something like a not found?

@RequestMapping(value = "/{name}", method = RequestMethod.GET)
@ResponseBody
public User getName(@PathVariable String name, ModelMap model)
{
    logger.debug("I am in the controller and got user name: " + name);

    /*
        Simulate a successful lookup for two users. This
        is where your real lookup code would go.
     */

    if ("name2".equals(name))
    {
        return new User("real name 2", name);
    }

    if ("name1".equals(name))
    {
        return new User("real name 1", name);
    }

    return null;
}

Upvotes: 2

Views: 13213

Answers (2)

WalkerDev
WalkerDev

Reputation: 1322

You could create an object specifically for returning error responses. That way, you can say whatever you want. For example:

@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<ResponseStatus> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex){

    ResponseStatus responseStatus = new ResponseStatus("400", "Bad Request. " + ex);
    responseStatus.setResponseStatusTime(timestampService.createTimestamp());
    HttpStatus status = HttpStatus.BAD_REQUEST;

    ResponseEntity<ResponseStatus> response = new ResponseEntity<ResponseStatus>(responseStatus, status);

    return response;
}

In this example you can see that there is a ResponseStatus object. This object contains a field for a status code, status message, date and time. You may not need date and time but I find it useful for when someone sends me an error they have seen, because then it is easy to track down exactly where it happened in our server logs.

Upvotes: 2

kevin847
kevin847

Reputation: 1068

Define a new exception class, e.g. ResourceNotFoundException and throw an instance of this from your annotated controller method getName.

Then also define an annotated exception handler method in your Controller class to handle that exception, and return a 404 Not Found status code, potentially logging it.

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public void handleResourceNotFoundException(ResourceNotFoundException ex)
{
    LOG.warn("user requested a resource which didn't exist", ex);
}

Or even returning some error message, using @ResponseBody annotation:

@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(value = HttpStatus.NOT_FOUND)
@ResponseBody
public String handleResourceNotFoundException(ResourceNotFoundException ex)
{
    return ex.getMessage();
}

Upvotes: 10

Related Questions