关于SpringMVC异常处理的实践总结
——我一直不太信任自己的记忆力,所以我把它们都写下来
在web项目中,用户访问了无效资源、系统内部错误等都需要给用户相应的回馈,比如说下面的404错误,我相信下面错误提示是用户和你都不想看到的。
类似异常有404,405,406,500 等,具体含义可以自行百度。这些异常处理可以让美工做几个漂亮的页面,然后在web.xml添加如下
<error-page> <error-code>404</error-code> <location>/albert/page/404</location> </error-page> <error-page> <error-code>405</error-code> <location>/albert/page/405</location> </error-page> <error-page> <error-code>500</error-code> <location>/albert/page/500</location> </error-page> <error-page> <exception-type>org.apache.shiro.authz.AuthorizationException</exception-type> <location>/albert/page/401</location> </error-page>
如果是是controller抛出的异常呐?
有两种方法来处理controller异常。
1.继承HandlerExceptionResolver,然后在mvc配置文件中添加这个异常resolver
/**
* @author albert
* 异常处理,不赞成使用,推荐使用@ExceptionHandler </br>
* 需要在mvc配置文件中添加
* <bean id="exceptionResolver" class="com.fh.resolver.MyExceptionResolver"></bean>
*/
@Deprecated
public class MyExceptionResolver implements HandlerExceptionResolver{
Logger logger = Logger.getLogger(this.getClass());
public ModelAndView resolveException(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex) {
ex.printStackTrace();
ModelAndView mv = new ModelAndView("error");
mv.addObject("exception", ex.toString().replaceAll("\n", "<br/>"));
return mv;
}
}
2.用注解的方式,一般都是定义一个抽象类,让所有的controller都继承它,controller方法捕获异常后在catch中都抛出同样的自定义异常
package com.albert.web.controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
public class BaseController {
Logger logger = Logger.getLogger(this.getClass());
@ExceptionHandler
public String exception(HttpServletRequest request,HttpServletResponse res, Exception e) {
logger.info("异常处理:"+e.getMessage());
RestController restController = AnnotationUtils.findAnnotation(this.getClass(), RestController.class);
if(restController==null){//返回页面
request.setAttribute("exceptionMessage", e.getMessage());
return "500";
}else{ //如果controller有@RestController注解,则返回json
PrintWriter writer = null;
try {
writer = res.getWriter();
} catch (IOException e1) {
e1.printStackTrace();
}
String json = "json_error";
writer.write(json);
writer.flush();
return null;
}
}
}
博主建议用第二种方式来统一处理异常,第一种方式会比较乱