考虑以下代码:
MyRest控制器:
@RestController
public class MyResponseEntity {
@GetMapping("/response")
public StreamingResponseBody getResponseEntity() {
return out -> {
throw new RuntimeException("I throw a RuntimeException");
};
}
}
myrestcontrolleradvice公司
@RestControllerAdvice
public class MyRestControllerAdvice extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {RuntimeException.class})
private ResponseEntity<Object> handleRestRuntimeException(final RuntimeException ex, final WebRequest request) {
return handleExceptionInternal(ex, new ApiError(INTERNAL_SERVER_ERROR), new HttpHeaders(), INTERNAL_SERVER_ERROR, request);
}
}
API错误
public class ApiError {
private HttpStatus status;
public ApiError(HttpStatus status) {
this.status = status;
}
// getter, setter
答复如下:
{
"status": "INTERNAL_SERVER_ERROR"
}{
"timestamp": "2021-04-23T13:51:41.438+0000",
"status": 500,
"error": "Internal Server Error",
"message": "I throw a RuntimeException",
"path": "/response"
}
我希望只返回第一个json对象:{“status”:“internal\u server\u error”}
我在ResonSentityExceptionHandler spring的类中发现了以下内容,但我不知道这是否会影响响应主体:
if (HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) {
request.setAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE, ex, WebRequest.SCOPE_REQUEST);
}
有人知道为什么这段代码返回两个json对象吗?
暂无答案!
目前还没有任何答案,快来回答吧!