简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM