0
我目前正在使用java-configured spring 4構建的api,它使用全局異常處理程序將服務器上引發的所有異常包裝到json對象中。除了由jdbcTemplate方法queryForObject()引發的EmptyResultDataAccessException之外,我已經設法解決了我遇到的每個異常。它目前正在爲我可以拋出的其他異常而努力,但在這個特定的例外上失敗。任何幫助,將不勝感激。@ControllerAdvice無法捕捉org.springframework.dao.EmptyResultDataAccessException
控制器忠告:
@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger logger = Logger.getLogger(GlobalExceptionHandler.class);
// 400
@ExceptionHandler(IncorrectResultSizeDataAccessException.class)
protected ResponseEntity<Object> handleEmptyResultDataAccessException(IncorrectResultSizeDataAccessException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
logger.info(ex.getClass()
.getName());
final ApiError apiError = new ApiError.Builder(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), "no results found").build();
return handleExceptionInternal(ex, apiError, headers, apiError.getStatus(), request);
}
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers,
HttpStatus status, WebRequest request) {
logger.info(ex.getClass()
.getName());
ApiError apiError = new ApiError.Builder(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(),
getAllErrorsFromBindingResult(ex.getBindingResult())).build();
return handleExceptionInternal(ex, apiError, headers, apiError.getStatus(), request);
}
//...
// 500
@ExceptionHandler({Exception.class, IOException.class, DaoException.class})
public ResponseEntity<Object> handleAll(final Exception ex, final WebRequest request) {
logger.info(ex.getClass()
.getName());
logger.error("error", ex);
final ApiError apiError = new ApiError.Builder(HttpStatus.BAD_REQUEST, ex.getLocalizedMessage(), "error occurred").build();
return new ResponseEntity<Object>(apiError, new HttpHeaders(), apiError.getStatus());
}
// Helper Methods
private List<String> getAllErrorsFromBindingResult(BindingResult ex) {
List<String> errors = new ArrayList<>();
ex.getFieldErrors()
.forEach(fieldError -> errors.add(fieldError.getField() + ": " + fieldError.getDefaultMessage()));
ex.getGlobalErrors()
.forEach(objectError -> errors.add(objectError.getObjectName() + ": " + objectError.getDefaultMessage()));
return errors;
}
}
應用程序配置:
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "app")
@Import(SwaggerConfig.class)
public class AppConfig extends WebMvcConfigurerAdapter {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
super.addViewControllers(registry);
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:7070");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
應用程序初始化程序:
public class AppInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(CeciAppConfig.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic dynamic = servletContext.addServlet("ceci-admin-service-dispatcher", new DispatcherServlet(ctx));
dynamic.setLoadOnStartup(1);
dynamic.addMapping("/");
}
}