最近看了一个比较不错的视屏分享给大家https://www.bilibili.com/video/av20669583/?p=6很适合我们新手学习。
在ssm项目中, 用户访问控制层,再到服务层,再到DAO层, 每一层都有可能出现异常。可以把每层的异常往上抛,抛给最外面的控制层,然后将这个错误显示到一个error.jsp页面上来提示用户网页出错了, 这样就比较人性化。 有时候控制层的方法是想返回json数据,并不想转到error.jsp界面上, 这种情况也可以在被处理。
步骤
建个exception包,存放异常处理类
CustomException类, 其中message存放异常消息
public class CustomException extends Exception{
public String message;
public CustomException(String message){
this.message = message;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
CustomExceptionResolver 类, 判断是带有@ResponseBody 。
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o,
Exception e) {
CustomException customException = null;
if (e instanceof CustomException){ //此错误是我们预期的错误
customException = (CustomException)e;
}else{ //非预期错误
customException = new CustomException("未知错误");
}
String message = customException.getMessage(); //错误文字信息
ModelAndView modelAndView = new ModelAndView();
//判断请求的类型, 是否是json
HandlerMethod handlerMethod = (HandlerMethod) o;
ResponseBody responseBody = handlerMethod.getMethod().getAnnotation(ResponseBody.class);
//是json请求, 则放回json数据
if (responseBody != null){
//设置状态码和信息
Map<String, Object> responseMap = new HashMap<String, Object>();
responseMap.put("code", "0");
responseMap.put("message", message);
String json = new Gson().toJson(responseMap);
System.out.println(json);
httpServletResponse.setContentType("UTF-8");
httpServletResponse.setContentType("application/json;charset=utf-8");
try{
httpServletResponse.getWriter().write(json);
httpServletResponse.getWriter().flush();;
}catch (IOException e1){
e1.printStackTrace();
}
return modelAndView;
}
modelAndView.addObject("message", message);
//不是json数据, 携带message到跳转到错误页面
modelAndView.setViewName("error");
return modelAndView;
}
}
控制层方法部分代码, 当用户名密码为空时, 抛出异常消息
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
throw new CustomException("用户名或密码不能为空");
}