我是@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);
}
异常处理方法:
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Error in the process")
@ExceptionHandler(Exception.class)
public void handleAllOtherException() {
}
答案 0 :(得分:6)
您可以使用@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");
}
应该使用HTTP 400代码生成响应并跟随正文:
{
"message": "Invalid data"
}
另请参阅Spring {注释@ExceptionHandler
的Spring JavaDoc,其中列出了可能的返回类型,其中之一是:
@ResponseBody
带注释的方法(仅限Servlet)来设置响应内容。返回值将使用消息转换器转换为响应流。
答案 1 :(得分:6)
替换
logrun() {
"$@"
}
通过
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Error in the process")
原因&#39;属性强制html渲染! 我已经浪费了一天的时间......
答案 2 :(得分:0)
ResponseEntity 类将默认在此处为您序列化JSON响应,并且 将RuntimeException抛出到您想要在应用程序中的任何位置
throw RuntimeException("Bad Request")
编写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);
}
}
输出:
{
"message": "Bad Request",
"httpStatus": 400
}