我已经实现了一个Spring Rest Controller,它使用StreamingResponseBody回传大型文件。但是,这些文件来自另一个系统,在流回这些文件时可能会出错。当这种情况发生时,我抛出了一个自定义异常(MyException)。我正在处理一个@ExceptionHandler实现中的异常,如下所示。我正在尝试设置响应httpstatus和错误消息,但总是收到http status 406。在返回StreamingResponseBody时,处理错误/异常的正确方法是什么?
@ExceptionHandler(MyException.class)
public void handleParsException( MyException exception, HttpServletResponse response) throws IOException
{
response.sendError(HttpStatus.INTERNAL_SERVER_ERROR.value(),exception.getMessage());
}发布于 2016-08-13 00:45:18
我解决了这个问题。客户端仅接受该文件类型作为可接受的响应。因此,当以html页面的形式返回错误时,我得到的是httpstatus 406。我只需要告诉客户机也接受html来显示消息。
发布于 2016-08-10 12:04:37
您应该以相同的方式处理所有错误。有很多选择。
我更喜欢下一步:
控制器建议
让一个实体发送一个通用的错误响应是一个好主意,例如:
public class Error {
private String code;
private int status;
private String message;
// Getters and Setters
}否则,要处理异常,您应该创建一个用@ControllerAdvice注释的类,然后创建用@ExceptionHandler注释的方法和您想要处理的一个或多个异常(可以是多个)。最后,返回包含所需状态代码的ResponseEntity<Error>。
public class Hanlder{
@ExceptionHandler(MyException.class)
public ResponseEntity<?> handleResourceNotFoundException(MyException
myException, HttpServletRequest request) {
Error error = new Error();
error.setStatus(HttpStatus.CONFLICT.value()); //Status you want
error.setCode("CODE");
error.setMessage(myException.getMessage());
return new ResponseEntity<>(error, null, HttpStatus.CONFLICT);
}
@ExceptionHandler({DataAccessException.class, , OtherException.class})
public ResponseEntity<?> handleResourceNotFoundException(Exception
exception, HttpServletRequest request) {
Error error = new Error();
error.setStatus(HttpStatus.INTERNAL_ERROR.value()); //Status you want
error.setCode("CODE");
error.setMessage(myException.getMessage());
return new ResponseEntity<>(error, null, HttpStatus.INTERNAL_ERROR);
}
}其他方式:
直接注释异常
另一种方法是使用状态和返回原因直接注释excetion:
@ResponseStatus(value=HttpStatus.CONFLICT, reason="Error with StreamingResponseBody")
public class MyError extends RuntimeException {
// Impl ...
}特定控制器中的异常处理程序
在@Controller的方法中使用带有@ExceptionHandler注释的方法来处理@RequestMapping异常:
@ResponseStatus(value=HttpStatus.CONFLICT,
reason="Error with StreamingResponse Body")
@ExceptionHandler(MyError.class)
public void entitiyExists() {
}https://stackoverflow.com/questions/38860240
复制相似问题