Java 发生异常时未调用ResponseEntityExceptionHandler

Java 发生异常时未调用ResponseEntityExceptionHandler,java,spring-mvc,spring-security,error-handling,spring-3,Java,Spring Mvc,Spring Security,Error Handling,Spring 3,我是春天的新手。我正在用SpringWebMVC开发RESTAPI。对于错误处理,我得到了这个链接 我已经尝试在我的项目中使用ResponseEntityExceptionHandler。但每当我的控制器抛出异常时,它永远不会到达这个ResponseEntityExceptionHandler 下面是我的代码片段 控制器 @Controller @RequestMapping("/hello") public class HelloController { private stati

我是春天的新手。我正在用SpringWebMVC开发RESTAPI。对于错误处理,我得到了这个链接

我已经尝试在我的项目中使用ResponseEntityExceptionHandler。但每当我的控制器抛出异常时,它永远不会到达这个ResponseEntityExceptionHandler

下面是我的代码片段

控制器

@Controller
@RequestMapping("/hello")
public class HelloController {  
    private static final Logger logger = Logger.getLogger(HelloController.class);
    @RequestMapping(value="/{name}", method=RequestMethod.GET)
    public @ResponseBody String greet(@PathVariable(value = "name")String name ) throws InvalidInputException, ResourceNotFoundException{
        logger.info("start greet() "+name );
        System.out.println("start greet() "+name);
        String message = null;
        if("".equalsIgnoreCase(name))
        {
            throw new InvalidInputException("Invalid Input");
        }
        List<String> names = new ArrayList<String>();
        names.add("Harshal");
        names.add("Smitesh");
        if(names.contains(name)){
            message = "Hello "+ name;
        }else{
            throw new ResourceNotFoundException("Requested Resource not found");
        }
        System.out.println("end greet");
        logger.info("end greet()");
        return message;
    }
}
例外处理程序

@ControllerAdvice
public class RestResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
    private static final Logger logger = Logger.getLogger(RestResponseEntityExceptionHandler.class);
    @ExceptionHandler(value={ResourceNotFoundException.class})
    @ResponseStatus(value=HttpStatus.NOT_FOUND)
    protected ResponseEntity<Object> handleResourceNotFound(RuntimeException ex, WebRequest request){
        logger.info("start handleResourceNotFound()");
        String bodyOfResponse = "Requested resource does not found";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return handleExceptionInternal(ex, bodyOfResponse, httpHeaders, HttpStatus.NOT_FOUND, request);
    }

    @ExceptionHandler(value={InvalidInputException.class})
    @ResponseStatus(value=HttpStatus.BAD_REQUEST)
    protected ResponseEntity<Object> handleInvalidInput(RuntimeException ex, WebRequest request){
        logger.info("start handleInvalidInput()");
        String bodyOfResponse = "Invalid Input";
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        return handleExceptionInternal(ex, bodyOfResponse, httpHeaders, HttpStatus.BAD_REQUEST, request);
    }
}
@ControllerAdvice
公共类RestResponseEntityExceptionHandler扩展ResponseEntityExceptionHandler{
私有静态最终记录器Logger=Logger.getLogger(RestResponseEntityExceptionHandler.class);
@ExceptionHandler(值={ResourceNotFoundException.class})
@ResponseStatus(值=HttpStatus.NOT_FOUND)
受保护的响应句柄资源查找(RuntimeException ex,WebRequest请求){
info(“start handleResourceNotFound()”;
字符串bodyOfResponse=“未找到请求的资源”;
HttpHeaders HttpHeaders=新的HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
返回handleExceptionInternal(例如,响应主体、HttpHeader、HttpStatus.NOT_FOUND、请求);
}
@ExceptionHandler(值={InvalidInputException.class})
@ResponseStatus(值=HttpStatus.BAD_请求)
受保护的响应handleInvalidInput(RuntimeException ex,WebRequest请求){
info(“start handleInvalidInput()”;
字符串bodyOfResponse=“无效输入”;
HttpHeaders HttpHeaders=新的HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
返回handleExceptionInternal(例如,响应主体、HttpHeader、HttpStatus.BAD_请求、请求);
}
}
调度器servlet

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-4.0.xsd">

   <context:component-scan base-package="com.practice.errorhandlerdemo.controller"/>
   <context:annotation-config/>  

</beans>

web.xml

<web-app>
    <display-name>ErrorHandlerDemo</display-name>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/my-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

ErrorHandlerDemo
调度员
org.springframework.web.servlet.DispatcherServlet
1.
上下文配置位置
/WEB-INF/my-servlet.xml
调度员
/

首先,检查您的配置是否考虑了您的
@ControllerAdvice
注释类:它是否位于Spring扫描的包中?您是否以其他方式将其声明为bean

此外,如果不需要它提供的所有异常映射,则不需要扩展
ResponseEntityExceptionHandler

编写异常处理的更简单方法:

@ControllerAdvice
public class RestResponseEntityExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    protected ResponseEntity<String> handleResourceNotFound(ResourceNotFoundException ex){

      return ResponseEntity
              .status(HttpStatus.NOT_FOUND)
              .body("Requested resource does not found");
    }

    @ExceptionHandler(InvalidInputException.class)
    protected ResponseEntity<String> handleInvalidInput(InvalidInputException ex){

      return ResponseEntity
              .badRequest()
              .body("Invalid Input");
    }
}
@ControllerAdvice
公共类ResponseEntityExceptionHandler{
@ExceptionHandler(ResourceNotFoundException.class)
受保护的响应句柄资源查找(ResourceNotFoundException ex){
返回响应性
.status(未找到HttpStatus.NOT_)
.body(“未找到请求的资源”);
}
@ExceptionHandler(InvalidInputException.class)
受保护的响应handleInvalidInput(InvalidInputException ex){
返回响应性
.badRequest()文件
.正文(“无效输入”);
}
}

请注意,Spring4.1中引入了
ResponseEntity
builder API,但您可以在4.0.x上使用常规构造函数。

我在SpringWebMVC4.2.5中也遇到了同样的问题。原因是
通过
DispatcherServlet
的异常IfNoHandlerFound
参数。默认情况下,它的值为
false
,因此所有错误都会生成
HttpServletResponse.SC_NOT_FOUND
servlet响应,并且没有异常


将其设置为true后,我的
@exceptionhandler
开始工作

报告了一些情况,其中
ResponseEntityExceptionHandler
@ControllerAdvice
都不工作

它们都应该将类下用
@ExceptionHandler
注释的方法编译到一个公共位置,所有控制器都可以从该位置引用


如果它对你不起作用。您可以将您的
@ExceptionHandler
方法添加到一个公共的
AbstractController
类中,该类由所有其他控制器扩展。

您只需要一些配置

在application.properties或application.yml中:

server.error.whitelabel.enabled=false
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
在springboot上加载配置文件:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "xx.xxx.xxxx")
@PropertySource("classpath:application.yml")
public class WebAppConfig {
}

问题在于@ExceptionHandler声明ResourceNotFoundException,而作为HandlereSourceNotFind的一个参数,您需要RuntimeException。参数exception和ExceptionHandler的值应匹配

因此,它应该是:

@ExceptionHandler(value={ResourceNotFoundException.class})
protected ResponseEntity<Object> handleResourceNotFound(ResourceNotFoundException ex, WebRequest request){
    
}
@ExceptionHandler(值={ResourceNotFoundException.class})
受保护的响应句柄资源查找(ResourceNotFoundException ex,WebRequest){
}
一些变通方法

  • 仔细检查是否为重写方法使用了正确的签名
  • 如果您使用任何IDE,请检查是否有任何@Override标记/符号/箭头可确保您的重写有效
  • 检查是否已经从项目的另一个类或依赖项的任何其他类扩展了
    ResponseEntityExceptionHandler
  • 将断点放在
    ResponseEntityExceptionHandler::handleException
    方法上
  • 对于
    NoHandlerFoundException
    ,您应该将DispatcherServlet配置为在未找到任何处理程序时引发异常

您是否找到了问题的解决方案?我也遇到了同样的问题…我认为RestResponseEntityExceptionHandler中的方法只有在重写ResponseEntityExceptionHandler中的方法时才会被使用。我的控制器建议类位于不同的包中。在controllers包中复制后,可能是因为您没有将RestResponseEntityExceptionHandler声明为@RestControllerWhy有人会在没有解释的情况下否决这个答案
ResponseEntityExceptionHandler
确实带来了额外的处理程序,但您不一定需要扩展它。关键是要有
@ControllerAdvice@ExceptionHandler(value={ResourceNotFoundException.class})
protected ResponseEntity<Object> handleResourceNotFound(ResourceNotFoundException ex, WebRequest request){
    
}