本文介绍了Spring MVC ExceptionHandler实现宁静和正常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想同时处理正常请求和休息/ ajax请求的异常。这是我的代码,

I want to handle exception for both normal and rest/ajax requests. Here is my code,

@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ModelAndView handleCustomException(Exception ex) {

        ModelAndView model = new ModelAndView("error");
        model.addObject("errMsg", ex.getMessage());
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        sw.toString();
        model.addObject("errTrace", sw);
        return model;

    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleAjaxException(Exception ex) {
        JSONObject model = new JSONObject();
        model.put("status", "error");
        model.put("errMsg", ex.getMessage());
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        sw.toString();
        model.put("errTrace", sw);

        return model.toString();
    }
}

这会给我一个错误,因为我无法使用@ ExceptionHandler(Exception.class)两次。那么解决方案是什么呢?

This will give me an error as I cant have @ExceptionHandler(Exception.class) twice. So what could be the solution?

推荐答案

请参阅@ControllerAdvice的配置:

see the configuration of @ControllerAdvice:http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html

因此您可以创建两个类(错误处理程序)并指定注释/ basePackages / assignibaleTypes

So you can create two classes(error handlers) and specify annotations/basePackages/assignibaleTypes

例如,对于REST(ajax),对控制器使用@RestController注释,您可以处理如下错误:

For example for REST(ajax) use @RestController annotation for your controllers and you can handle errors like this:

@ControllerAdvice(annotations = RestController.class)
public class MyExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleAjaxException(Exception ex) {
        ...
    }
}

在其他情况下可能是错误处理程序wi注释

for other cases it can be error handler with annotation

@ControllerAdvice(annotations = Controller.class)

这篇关于Spring MVC ExceptionHandler实现宁静和正常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 04:44