当前位置: 首页 > 知识库问答 >
问题:

Spring启动应用程序中的自定义异常失败

夔宏深
2023-03-14
@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(value = {HttpMessageNotReadableException.class})
    protected ResponseEntity<ExceptionResDto> handleException(){
        ExceptionResDto response = new ExceptionResDto();
        .......
        return new ResponseEntity<ExceptionResDto>(response, new HttpHeaders(), HttpStatus.BAD_REQUEST);
    }

但如果我做了这样的事情,它是有效的!!!(重写当前可用的方法以捕获HttpMessageNotReadableException)

@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
    .... //customized code
        return new ResponseEntity<Object>(response, new HttpHeaders(), status);
}

我的问题是@exceptionHandler(value={customexception.class})只用于自定义异常?不能习惯于现有的更一般的异常?为了自定义这样的一般异常,我们总是需要重写它们原来的异常处理方法吗?

下面是日志结果。

(AbstractAutowireCapableBeanFactory.java:409)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1620)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
    ... 49 common frames omitted
2020-05-03 14:38:41.565 [main] ERROR o.s.boot.SpringApplication -
                Application startup failed 
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handlerExceptionResolver' defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerExceptionResolver]: Factory method 'handlerExceptionResolver' threw exception; nested exception is java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.http.converter.HttpMessageNotReadableException]: {protected org.springframework.http.ResponseEntity lk.crm.dialog.config.CustomExceptionHandler.myHandleException(), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest)}
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:314)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151)
    at lk.crm.dialog.Application.main(Application.java:17)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.base/java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.boot.loader.MainMethodRunner.run(MainMethodRunner.java:48)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:87)
    at org.springframework.boot.loader.Launcher.launch(Launcher.java:50)
    at org.springframework.boot.loader.JarLauncher.main(JarLauncher.java:51)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerExceptionResolver]: Factory method 'handlerExceptionResolver' threw exception; nested exception is java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.http.converter.HttpMessageNotReadableException]: {protected org.springframework.http.ResponseEntity lk.crm.dialog.config.CustomExceptionHandler.myHandleException(), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest)}
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 26 common frames omitted
Caused by: java.lang.IllegalStateException: Ambiguous @ExceptionHandler method mapped for [class org.springframework.http.converter.HttpMessageNotReadableException]: {protected org.springframework.http.ResponseEntity lk.crm.dialog.config.CustomExceptionHandler.myHandleException(), public final org.springframework.http.ResponseEntity org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest)}
    at org.springframework.web.method.annotation.ExceptionHandlerMethodResolver.addExceptionMapping(ExceptionHandlerMethodResolver.java:109)
    at org.springframework.web.method.annotation.ExceptionHandlerMethodResolver.<init>(ExceptionHandlerMethodResolver.java:76)
    at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.initExceptionHandlerAdviceCache(ExceptionHandlerExceptionResolver.java:269)
    at org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver.afterPropertiesSet(ExceptionHandlerExceptionResolver.java:245)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.addDefaultHandlerExceptionResolvers(WebMvcConfigurationSupport.java:883)
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration.configureHandlerExceptionResolvers(WebMvcAutoConfiguration.java:428)
    at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.handlerExceptionResolver(WebMvcConfigurationSupport.java:826)
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$901be0b6.CGLIB$handlerExceptionResolver$41(<generated>)
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$901be0b6$$FastClassBySpringCGLIB$$b8bb3bfc.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:356)
    at org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$EnableWebMvcConfiguration$$EnhancerBySpringCGLIB$$901be0b6.handlerExceptionResolver(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.base/java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 27 common frames omitted

共有1个答案

郝原
2023-03-14

为什么要在异常处理程序中引发另一个异常?我想您想要的是在中心位置(您的处理程序)捕获抛出的异常,也许用更多的细节记录错误(我绝对建议这样做),并用汇总的细节给客户机一个非常好的响应。

不是抛出另一个异常,而是抛出一个自定义异常模型,该模型保存您希望以json格式返回的内容。

    public class CustomExceptionModel{

    private String message
    private HttpStatus httpStatus
    private ZonedTime timestamp

    public Custom{ExceptionModel (String message, HttpStatus httpStatus){
this.message = message;
this.httpStatus = httpStatus;
this.timeStamp = ZonedTime.now();
    }
    }

你的经办人应该是这样的

@ExceptionHandler(value = {HttpMessageNotReadableException.class})
    protected ResponseEntity<ExceptionResDto> handleException(HttpMessageNotReadableException ex){
       log.severe("Put details here ;) ");
        return new ResponseEntity<CustomExceptionModel>(new CustomExceptionModel(ex.getMessage(), ex.getStatus()), HttpStatus.BAD_REQUEST);
    }
 类似资料:
  • 问题内容: 我可以使用Maven编译并启动Spring项目: 但是,当我使用(包括)将所有jar组合到一个文件中时,在执行过程中总是会得到一个: 我还尝试将架构定义(即等)直接附加到类路径,但是没有成功。 问题答案: Spring命名空间处理程序使用文件和解析。由于具有这些名称的文件存在于不同的Spring jar中,因此可能只有其中一个保留在目标jar之后。 也许您可以手动合并这些文件,然后以某

  • 我有一个使用restful api的Spring Boot客户机。应用程序中有任何密钥条目,而不是在java类中硬编码RESTAPI的IP地址。我可以使用的属性? 如果没有,我可以创建一个自定义条目吗? 谢啦

  • 我是spring的初学者,希望这样做示例项目…我有一个数据库,我想连接到它…我使用了像AutoWired和service这样的注释。但有个问题我解决不了 Controller包中的RegisterationController具有我要调用的服务: 第一个包中的DataManagement类: 第一包中的StudentAccountRepository: 第一包中得学生帐户..引用数据库中的表: M

  • 最近,我遇到了一种情况,即基于Spring的应用程序在访问类(A)中的自动连接字段时抛出“NullPointerApplication”。被自动连接的豆子也用于其他类(B和C)。这些类(B和C)在访问该bean时工作正常。 当我重新启动应用程序时,一切正常。如前所述,如果bean自动连接失败,则类bean创建应失败,应用程序不应启动。相反,应用程序运行良好(A类除外),并且找不到“无法自动连线”异

  • “Spring-Boot-AutoConfigure”,版本:'2.4.1'

  • 我试图创建一个应用程序,但我一直遇到相同的运行时异常。我已经和它斗争了好几天,我不知道如何修复它。任何建议都将不胜感激!这是我在Java中的第一个相当长的项目,所以我决心解决它;只是有相当多的麻烦,我不知道如何克服这一点。