我正在尝试捕获在我的StreamingResponseBody实现中抛出的异常,我可以看到异常被抛出在类内部,但是抛出的异常对方法体或我的控制器通知不可见。因此,我的处理似乎都不起作用,只是想知道在这种情况下,哪种方法才是处理异常的正确方法。
@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);
}
}
};
}我希望我的ControllerAdvice会返回一个状态为500的ResponseEntity。
发布于 2019-06-18 23:09:48
我发现在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;
}
}然后在@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());
}其中ErrorDTO只是一个简单的带有两个字段的DTO:
@Value
@Builder
public class ErrorDTO {
private final String message;
private final String description;
}https://stackoverflow.com/questions/56651902
复制相似问题