简体   繁体   English

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

[英]How to get response in JSON format using @ExceptionHandler in Spring MVC

I am new to this @ExceptionHandler .我是这个@ExceptionHandler的新手。 I need to return response in JSON format if there is any exception.如果有任何异常,我需要返回 JSON 格式的响应。 My code is returning response in JSON format if the operation is successful.如果操作成功,我的代码将以 JSON 格式返回响应。 But when any exception is thrown it is return HTML response as I have used @ExceptionHandler .但是当抛出任何异常时,它会返回 HTML 响应,因为我使用@ExceptionHandler

Value and reason in @ResponseStatus is coming properly but in HTML. How can I can change it to a JSON response? @ResponseStatus中的值和原因正常,但在 HTML 中。如何将其更改为 JSON 响应? Please help.请帮忙。

In my controller class i have this methods:在我的 controller class 中,我有以下方法:

@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);
}

Exception handling method:异常处理方法:

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

}

You can annotate the handler method with @ResponseBody and return any object you want and it should be serialized to JSON (depending on your configuration of course).您可以使用@ResponseBody注释处理程序方法并返回您想要的任何对象,并且应该将其序列化为 JSON(当然取决于您的配置)。 For instance:例如:

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");
}

which should produce response with HTTP 400 code and following body:它应该产生带有 HTTP 400 代码和以下正文的响应:

{
    "message": "Invalid data"
}

Also see Spring JavaDoc for @ExceptionHandler which lists possible return types, one of which is:另请参阅@ExceptionHandler Spring JavaDoc,其中列出了可能的返回类型,其中之一是:

@ResponseBody annotated methods (Servlet-only) to set the response content. @ResponseBody注释方法(仅限 Servlet)来设置响应内容。 The return value will be converted to the response stream using message converters.返回值将使用消息转换器转换为响应流。

Replace代替

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Error in the process")

by经过

@ResponseStatus(value = HttpStatus.NOT_FOUND)

the 'reason' attribute force html render! 'reason' 属性强制 html 渲染! I've waste 1 day on that.....我已经浪费了1天.....

ResponseEntity class will serialize you JSON response by default here and throw RuntimeException wherever you want to in application ResponseEntity类将在这里默认序列化您的 JSON 响应,并在应用程序中的任何位置抛出 RuntimeException

throw RuntimeException("Bad Request")

Write GlobalExceptionHandler class编写 GlobalExceptionHandler 类

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    private class JsonResponse {
        String message;
        int httpStatus ;

        public JsonResponse() {
        }

        public JsonResponse(String message, int httpStatus ) {
            super();
            this.message = message;
            this.httpStatus = httpStatus;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

        public int getHttpStatus() {
            return httpStatus;
        }

        public void setHttpStatus(int httpStatus) {
            this.httpStatus = httpStatus;
        }

    }

    @ExceptionHandler({ RuntimeException.class })
    public ResponseEntity<JsonResponse> handleRuntimeException(
    Exception ex, WebRequest request) {
      return new ResponseEntity<JsonResponse>(
              new JsonResponse(ex.getMessage(), 400 ), new HttpHeaders(), HttpStatus.BAD_REQUEST);
    }

}

Output:输出:

{
    "message": "Bad Request",
    "httpStatus": 400
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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