我正在使用Spring Boot,我在我的业务逻辑代码中使用异常类。一个可能看起来像这样:
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class ExternalDependencyException extends RuntimeException {
public ExternalDependencyException() {
super("External Dependency Failed");
}
public ExternalDependencyException(String message) {
super(message);
}
}
现在有Exception,其中没有预定义的Http Status代码是合适的,所以我想使用像460或类似的状态代码,它仍然是免费的,但是注释ResponseStatus
只接受来自枚举HttpStatus
。有没有办法在java spring引导环境中使用自定义状态代码实现Exception类?
答案 0 :(得分:5)
我不知道如何使用@ResponseStatus执行此操作。
要解决的一种方法是使用@RestControllerAdvice来解决此问题。 这将允许您自定义返回异常的方式。
@RestControllerAdvice
public class WebRestControllerAdvice {
@ExceptionHandler(ExternalDependencyException.class)
public String handleGitlabException(ExternalDependencyException ex, HttpServletResponse response) {
try {
response.sendError(460);
} catch (Exception e) {
e.printStackTrace();
}
return ex.getMessage();
}
}
答案 1 :(得分:1)
通常,@ mdeterman的回答很好,但是我相信正确的做法是setStatus进行响应,而不是直接sendError。示例:
error: no matching member function for call to 'find'
return (m_associates.find(x) != m_associates.end());
~~~~~~~~~~~~^~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_set.h:798:7: note: candidate function not viable: 1st argument ('const T *') would lose const qualifier
find(const key_type& __x) const
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_set.h:804:2: note: candidate function template not viable: 'this' argument has type 'const std::set<T *>', but method is not marked const
find(const _Kt& __x)
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_set.h:794:7: note: candidate function not viable: 'this' argument has type 'const std::set<T *>', but method is not marked const
find(const key_type& __x)
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_set.h:810:2: note: candidate template ignored: substitution failure [with _Kt = const T *]: no matching member function for call to '_M_find_tr'
find(const _Kt& __x) const
^
似乎仅由于@RestControllerAdvice才有可能。 @ControllerAdvice在视图解析器级别重置状态代码(出于某些奇怪的原因)。 同样重要的是要了解:任何自定义状态代码(在org.apache.http.HttpStatus-RFC1945,RFC2616和 RFC2518)如果客户端服务基于spring,则会导致UnknownHttpStatusCodeException。
答案 2 :(得分:0)
在Spring Boot 2.1.8.RELEASE中,我做了类似的事情,但是没有使用HttpServletResponse:
@RestControllerAdvice
public class RestExceptionHandler {
@ExceptionHandler(MyCustomException.class)
@ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
public ApiErrorResponse handleTemplateEngineException(MyCustomException ex) {
//custom ApiErrorResponse class
return ApiErrorResponse.builder()
.status(HttpStatus.NOT_ACCEPTABLE)
.errorCode("NOT_ACCEPTABLE")
.message(ex.getLocalizedMessage()).build();
}
}