Popcorn
Popcorn

Reputation: 5348

In Spring, Is there a way to return different Content-Type values for the header?

I would like to set the produces = text/plain to produces = application/json when I encounter an error.

@RequestMapping(value = "/v0.1/content/body", method = RequestMethod.GET, produces = "text/plain")
@ResponseBody
public Object getBody(@RequestParam(value = "pageid") final List<String> pageid, @RequestParam(value = "test") final String test) {

    if (!UUIDUtil.isValid(pageid)) {
        Map map = new HashMap();
        map.put("reason", "bad pageId");
        map.put("pageId", pageId);
        map.put("test", test);

        return new ResponseEntity<Object>(map, HttpStatus.BAD_REQUEST);
    }

    return "hello";
}

The problem with this code is that it doesn't print the error as json when I send an invalid pageId. It gives me a HTTP 406 error Not acceptable, because it expects to produce text/plain but I didn't return a String.

Upvotes: 1

Views: 1026

Answers (1)

Vidya
Vidya

Reputation: 30300

The cleanest way to handle errors is to use @ExceptionHandler:

@ExceptionHandler(EntityNotFoundException.class) //Made up that exception
@ResponseBody
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public ErrorObject handleException(Exception e) {
    return new ErrorObject(e.getMessage());
}

Then assuming you've configured your resolvers properly and put the right JSON serialization library in the classpath, the instance of ErrorObject will be returned to the client as a JSON response.

Of course you can set up multiple @ExceptionHandler methods as needed.

Upvotes: 1

Related Questions