Spring 中的自定义 Http 状态代码 [英] Custom Http Status Code in Spring
问题描述
我正在使用 Spring Boot 并且在我的业务逻辑代码中使用异常类.一个可能看起来像这样:
I am using Spring Boot and I am using Exception Classes thoughout my business logic code. One might look like this:
@ResponseStatus(HttpStatus.BAD_REQUEST)
public class ExternalDependencyException extends RuntimeException {
public ExternalDependencyException() {
super("External Dependency Failed");
}
public ExternalDependencyException(String message) {
super(message);
}
}
现在有异常,没有预定义的 Http 状态代码适合,所以我想使用像 460 或类似的状态代码,它仍然是免费的,但注释 ResponseStatus
只是接受枚举 HttpStatus
中的值.有没有办法在java spring boot环境中实现带有自定义状态码的Exception类?
Well now there are Exception, where no predefined Http Status code is fitting, so I would like to use a status code like 460 or similar, which is still free, but the annotation ResponseStatus
just accepts values from the enum HttpStatus
. Is there a way to achieve an Exception class with a custom status code in the java spring boot environment?
推荐答案
我不知道有什么方法可以用 @ResponseStatus.
I'm not aware of a way to do this with @ResponseStatus.
解决这个问题的一种方法是使用 @RestControllerAdvice.这将允许您自定义返回异常的方式.
One way to solve is this issue is with @RestControllerAdvice. This will allow you to customize how you return your Exception.
@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();
}
}
这篇关于Spring 中的自定义 Http 状态代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!