[英]Bean creation errors for request-scoped beans
When a Spring bean is annotated with SCOPE_REQUEST
, it is created and destroyed every time a HTTP request is received by the servlet. 当使用SCOPE_REQUEST
注释Spring bean时,每次servlet接收到HTTP请求时都会创建并销毁它。 If this bean creation fails, a server error is sent back to the caller. 如果此Bean创建失败,则会将服务器错误发送回调用方。
In this trivial example, the creation of the MyInputs
bean is dependent on the contents of the HTTP request. 在这个简单的示例中, MyInputs
bean的创建取决于HTTP请求的内容。
@Configuration
class ApplicationConfiguration {
@Bean
@Scope(scopeName = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
public MyInputs myInputs(HttpServletRequest request) {
String header1 = request.getHeader("header1");
if (header1 == null) {
throw new MyException("header1 is missing");
}
return new MyInputs(header1);
}
}
If the HTTP request does not contain a required header, a BeanCreationException
will be thrown. 如果HTTP请求不包含必需的标头,则将抛出BeanCreationException
。 This is translated into an unhelpful "500 Internal Server Error" response. 这被转换为无用的“500内部服务器错误”响应。
I would like to return a more user-friendly response code and body, for example, a "400 Bad Request" with a helpful message. 我想返回一个更加用户友好的响应代码和正文,例如,“400 Bad Request”和一条有用的消息。 How do I customize this response translation? 如何自定义此响应转换? I cannot find any lifecycle hooks which will allow this. 我找不到任何允许这样做的生命周期钩子。
Note: This is how the request-scoped bean is consumed: 注意:这是使用请求范围的bean的方式:
@RestController
public class MyController {
private final Provider<MyInputs> myInputsProvider;
@Autowired
public MyController(Provider<MyInputs> myInputsProvider) {
this.myInputsProvider = myInputsProvider;
}
@GetMapping("/do-stuff")
public void doStuff() {
// Get the inputs for the current request
MyInputs myInputs = myInputsProvider.get();
// ...
}
}
You can use @ControllerAdvice
annotation in order to handle exceptions after are thrown. 您可以使用@ControllerAdvice
批注来处理抛出后的异常。
Also you need to use @ExceptionHandler
in order to handle the exception. 您还需要使用@ExceptionHandler
来处理异常。
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MyException.class)
public final ResponseEntity<CustomError> handleException(MyException ex, WebRequest request) {
CustomError error = new CustomError();
error.setMessage(ex.getMessage());
error.setStatus(HttpStatus.BAD_REQUEST);
return new ResponseEntity<>(error, null, HttpStatus.BAD_REQUEST);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.