[英]Exception handling in StreamingResponseBody
I'm trying to catch an exception thrown in my implementation of StreamingResponseBody, I can see the exception being thrown inside the class however the thrown exception isn't visible to the method body or my Controller Advice. 我正在尝试捕获我在StreamingResponseBody的实现中抛出的异常,我可以看到异常被抛出到类中但是抛出的异常对于方法体或我的Controller建议是不可见的。 So none of my handling seems to work, just interested to know which is the correct way to handle exceptions in this case. 所以我的处理似乎都没有用,只是有兴趣知道在这种情况下处理异常的正确方法。
@GetMapping(path = "/test", produces = "application/json")
public StreamingResponseBody test(@RequestParam(value = "var1") final String test)
throws IOException{
return new StreamingResponseBody() {
@Override
public void writeTo(final OutputStream outputStream) throws IOException{
try {
// Some operations..
} catch (final SomeCustomException e) {
throw new IOException(e);
}
}
};
}
I would expect my ControllerAdvice to return an ResponseEntity with a Http Status of 500. 我希望我的ControllerAdvice返回一个Http Status为500的ResponseEntity。
The best way I discovered to handle errors/exceptions in the web environment is to create your custom exception with the disabled stack trace, and handle it with @ControllerAdvice
. 我发现在Web环境中处理错误/异常的最佳方法是使用禁用的堆栈跟踪创建自定义异常,并使用@ControllerAdvice
处理它。
import lombok.Getter;
import org.springframework.http.HttpStatus;
public class MyException extends RuntimeException {
@Getter private HttpStatus httpStatus;
public MyException(String message) {
this(message, HttpStatus.INTERNAL_SERVER_ERROR);
}
public MyException(String message, HttpStatus status) {
super(message, null, false, false);
this.httpStatus = status;
}
}
And then handle it in @ControllerAdvice
like this: 然后在@ControllerAdvice
处理它,如下所示:
@ExceptionHandler(MyException.class)
public ResponseEntity handleMyException(MyException exception) {
return ResponseEntity.status(exception.getHttpStatus()).body(
ErrorDTO.builder()
.message(exception.getMessage())
.description(exception.getHttpStatus().getReasonPhrase())
.build());
}
where ErrorDTO
is just a simple DTO with two fields: 其中ErrorDTO
只是一个包含两个字段的简单DTO:
@Value
@Builder
public class ErrorDTO {
private final String message;
private final String description;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.