【问题标题】:@ExceptionHandler response not working in Tomcat@ExceptionHandler 响应在 Tomcat 中不起作用
【发布时间】:2016-10-02 06:19:12
【问题描述】:

我正在使用 Spring MVC 处理异常。我正在使用@ControllerAdvice 和@ExceptionHandler。为了返回 JSON,我尝试了两种情况:@ResponseBody 和 ResponseEntity。

这是我的控制器:

@ControllerAdvice
public class GlobalExceptionController {

@ExceptionHandler(CustomGenericException.class)
@ResponseBody
public ErrorResource handleCustomException(CustomGenericException ex) {

        ErrorResource errorResource=new ErrorResource("Example 1");
    errorResource.error=ex.getErrCode();

    return errorResource;

}

@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResource> handleAllException(Exception ex) {

    ErrorResource errorResource=new ErrorResource("Example 2");
    errorResource.error=ex.getMessage();

    return new ResponseEntity<ErrorResource>(errorResource,HttpStatus.NOT_FOUND);

}

}
class ErrorResource {
public String error;

public ErrorResource(String a ){error=a;}
}

我正在使用 maven 的 tomcat 7 插件来运行和调试应用程序,所以当我调试时,我可以看到 @ExceptionHandler 正在触发并执行 return 语句。但我得到的是 HTTP 500 错误,而不是接收 JSON:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.mkyong.web.exception.CustomGenericException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)

如果我返回视图或 ModelView 正在工作,但每当我尝试返回 ResponseBody 或 ResponseEntity 时,我仍然会收到相同的错误。

最后,如果我不使用 tomcat,而是使用 SpringBoot 来运行应用程序,我没有收到错误消息,并且我得到了我应该收到的响应:

{"error":"E888"}

为什么不能使用 Tomcat?

谢谢。

【问题讨论】:

  • 由于行为完全在 servlet 内,根本不是 Tomcat 问题

标签: java spring maven tomcat exception-handling


【解决方案1】:

原因在于 Spring 处理异常的方式。在没有 Boot 的普通 Spring 应用程序中 @ExceptionHandler 由 exceptionResolver 使用,它适用于浏览器用户,或者换句话说,当异常到达时它被认为是渲染页面。您的请求流不会通过 contenNegotiationResolver ,因此您会继续收到异常。在 Spring Boot 中,请求生命周期的流程被认为是为浏览器用户和非浏览器用户之类的应用程序管理异常,因此它可以工作,我建议参考官方文档以获取更多详细信息。

更新以在评论中回答。

在 Spring Boot 中,您以非常不同的方式管理异常,尊重普通 spring mvc 应用程序的许多细节,我建议在链接spring boot doc 上查看文档。 如果您想使用普通的 Spring Web 应用程序,我可以建议使用方面。您可以使用普通的@ExceptionHandler 用法并返回一个ModelView 实现来响应@Controller 类中没有@ResponseBody 的普通页面请求,并创建一个方面来管理用@ResponseBody 注释的方法的异常并返回ResponseEntity .这方面可能是如下所示,请注意,在此示例中,我开发了切入表达式,用于拦截在 com.springapp.mvc 包下返回 ResponseEntity 的方法:

方面:

@Aspect
@Component
public class GlobalExceptionRestAOPController {


    private ObjectMapper objectMapper = new ObjectMapper();

    @Around("execution(org.springframework.http.ResponseEntity com.springapp.mvc..*(..))")
    public Object manageException(ProceedingJoinPoint pjp) throws Throwable{
        Object result;
        try{
            result = pjp.proceed();
        } catch (Exception e){
            // log it.
                       result = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).contentType(MediaType.APPLICATION_JSON).body(objectMapper.writeValueAsString(new ExceptionReport(e.toString())));

        }

        return result;
    }
}

class ExceptionReport{
    private final String error;

    public ExceptionReport(String error) {
        this.error = error;
    }

    public String getError() {
        return error;
    }
}

别忘了在你的配置中插入

xml 样式:

<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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <aop:aspectj-autoproxy/>

    <context:component-scan base-package="com.springapp.mvc"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

...
</beans>    

Java 风格:

@Configuration
@EnableAspectJAutoProxy
...
class AspectConfiguration{
...
}

控制器:

@Controller
public class HelloController {


    @RequestMapping(value = "/jsonHelloEx", method = RequestMethod.GET, produces = "application/json")
    public ResponseEntity printWelcomeWithException() {
        String nullableString = null;
        nullableString.equals("");
        return ResponseEntity.ok("Hello");
    }
}

希望对你有帮助

【讨论】:

  • 那么,如果我想处理这些异常,我必须在我的应用程序中实现 Spring Boot,然后从那里运行它?这是唯一的选择吗?
  • 我用一个例子更新了我的答案,我希望它可以帮助您找到问题的解决方案
  • 感谢您的帮助。实际上,我一直在阅读一些文档,并将我的应用程序迁移到 Spring Boot。谢谢你为我做的一切。我给你答案了。
【解决方案2】:

@ExceptionHandler 方法没有 @ResponseBody 返回类型,它只能返回 ModelViewString 被转换为视图

返回类型可以是String,解释为视图名 或 ModelAndView 对象。

查看这里了解更多信息:Spring @ExceptionHandler does not work with @ResponseBody

【讨论】:

  • 这在 Spring 的后期版本中发生了变化。见link
猜你喜欢
  • 2018-12-10
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多