当用 SCOPE_REQUEST
注释 Spring bean 时,每次 servlet 收到 HTTP 请求时都会创建和销毁它。如果此 bean 创建失败,则会将服务器错误发送回调用者。
在这个简单的示例中,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);
}
}
如果 HTTP 请求不包含必需的 header ,将抛出 BeanCreationException
。这被翻译成无用的“500 Internal Server Error”响应。
我想返回一个对用户更友好的响应代码和正文,例如,带有有用消息的“400 Bad Request”。如何自定义此响应翻译?我找不到任何允许这样做的生命周期 Hook 。
注意:这是请求范围的 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();
// ...
}
}
最佳答案
您可以使用@ControllerAdvice
注解来处理抛出的异常。
您还需要使用@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);
}
}
关于java - 请求范围的 bean 的 bean 创建错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57169562/