【问题标题】:How to declare ExceptionHandlerExceptionResolver in java code?如何在java代码中声明ExceptionHandlerExceptionResolver?
【发布时间】:2013-11-20 07:29:14
【问题描述】:
【问题讨论】:
标签:
java
spring
exception-handling
【解决方案1】:
您必须手动将您的处理程序添加到处理程序列表中(在下面的示例中,我使用了一个 SIMpleMappingExceptionsResolver,但您可以使用您自己的实现):
package eu.anastasis.readingtrainer.configuration;
import java.util.List;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
@Configuration
@EnableWebMvc
public class ConfigurationAdapter extends WebMvcConfigurerAdapter {
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> exceptionResolvers) {
exceptionResolvers.add(new SimpleMappingExceptionResolver());
}
}
请注意,这样你会覆盖你可能设置的任何@ControllerAdvice + @ExceptionHandler(我不知道如何结合这两种策略)。
【解决方案2】:
就像对@Andrea Pegoretti 答案的更新一样,
在 Spring 5.X.X WebMvcConfigurerAdapter 中已弃用,而是使用 WebMvcConfigurer 接口;详情请参考link。