如何使用Spring MVC中的@ExceptionHandler以JSON格式获取响应

sou*_*jee 5 spring json exception spring-mvc

我是新手@ExceptionHandler.如果有任何异常,我需要以JSON格式返回响应.如果操作成功,我的代码将以JSON格式返回响应.但是当抛出任何异常时,它就像我使用的那样返回HTML响应@ExceptionHandler.

@ResponseStatus正确的价值和理由正在以HTML形式出现.如何将其更改为JSON响应?请帮忙.

在我的控制器类中,我有这样的方法:

@RequestMapping(value = "/savePoints", method = RequestMethod.POST, consumes = "application/json", produces = "application/json;charset=UTF-8")
public @ResponseBody
GenericResponseVO<TestResponseVO> saveScore(
        @RequestBody(required = true) GenericRequestVO<TestVO> testVO) {
    UserContext userCtx = new UserContext();
    userCtx.setAppId("appId");
    return gameHandler.handle(userCtx, testVO);
}
Run Code Online (Sandbox Code Playgroud)

异常处理方法:

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Error in the process")
@ExceptionHandler(Exception.class)
public void handleAllOtherException() {

}
Run Code Online (Sandbox Code Playgroud)

Boh*_*rdt 8

您可以使用@ResponseBody并返回所需的任何对象来注释处理程序方法,并且应该将其序列化为JSON(具体取决于您的配置).例如:

public class Error {
    private String message;
    // Constructors, getters, setters, other properties ...
}

@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Error handleValidationException(MethodArgumentNotValidException e) {
    // Optionally do additional things with the exception, for example map
    // individual field errors (from e.getBindingResult()) to the Error object
    return new Error("Invalid data");
}
Run Code Online (Sandbox Code Playgroud)

应该使用HTTP 400代码和以下正文生成响应:

{
    "message": "Invalid data"
}
Run Code Online (Sandbox Code Playgroud)

另请参阅Spring JavaDoc,@ExceptionHandler其中列出了可能的返回类型,其中之一是:

@ResponseBody带注释的方法(仅限Servlet)来设置响应内容.返回值将使用消息转换器转换为响应流.


C2d*_*ric 6

更换

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Error in the process")
Run Code Online (Sandbox Code Playgroud)

通过

@ResponseStatus(value = HttpStatus.NOT_FOUND)
Run Code Online (Sandbox Code Playgroud)

'reason'属性强制html渲染!我浪费了一天......