[英]Bean creation errors for request-scoped beans
当使用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请求不包含必需的标头,则将抛出BeanCreationException
。 这被转换为无用的“500内部服务器错误”响应。
我想返回一个更加用户友好的响应代码和正文,例如,“400 Bad Request”和一条有用的消息。 如何自定义此响应转换? 我找不到任何允许这样做的生命周期钩子。
注意:这是使用请求范围的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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.