为什么要异常统一处理
用户体验很重要
提高开发效率
不需要重复处理异常
自定义异常类
import lombok.Getter;import lombok.Setter;@Getter@Setterpublic class MyException extends RuntimeException { private Integer code; public MyException(String msg){ super(msg); } public MyException(Integer code,String msg){ super(msg); this.code=code; }}
自定义枚举
import lombok.Getter;import lombok.Setter;@Getterpublic enum ResultEnum { SUCCESS(200,"成功"), FAIL(100,"失败"), EXCEPTION(300,"系统异常"), UNLOGIN(201,"未登录"), FORBIDDEN(403, "您没有权限访问!"), NOT_FOUND(404, "资源不存在!"), ERROR(500, "服务器内部错误!"); private Integer code; private String msg; private ResultEnum(Integer code,String msg){ this.code=code; this.msg=msg; } public void setCode(Integer code){ this.code=code; }}
全局异常统一处理
import com.xyl.xylshiro.exception.MyException;import org.apache.shiro.authz.AuthorizationException;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestControllerAdvice;import javax.servlet.http.HttpServletRequest;import java.util.HashMap;import java.util.Map;@ControllerAdvicepublic class MyExceptionAdviceController { /** * 全局异常捕捉处理 * @param e * @return */ @ExceptionHandler(Exception.class) public String errorHandler(Exception e, HttpServletRequest request) { request.setAttribute("javax.servlet.error.status_code",ResultEnum.ERROR.getCode()); Map<String,Object> map = new HashMap<String,Object>(); map.put("code",ResultEnum.ERROR.getCode()); map.put("msg",e.getMessage()); request.setAttribute("ext", map);//放在request中的数据,在前端页面中都可以取出来 /* 在Freemark中这里需要注意的是error跳转页面, 前端错误页面需要放在templates/error页面下如果需要自己改的话 需要自定义模板路径*/ return "forward:/error"; }}
错误页面放置
本地测试localhost:8080/exception
@RequestMapping("/exception") public ResponseVo exception(String name, String pwd) throws Exception { String realname = "xxxxx"; String realPwd = "123"; if (null != name && name.equals("xx")) { throw new Exception("系统异常!"); } if (StringUtils.isEmpty(name) || StringUtils.isEmpty(pwd)) { throw new MyException("参数必须传!"); } else if (!name.equals(realname) || !pwd.equals(realPwd)) { throw new MyException("用户名或密码不正确!"); } else if (name.equals("aa")) { throw new MyException(200, "用户名存在!"); } String info = "你好[" + name + "]!"; ResponseVo success = ResultUtil.success("输入成功", info); return ResultUtil.success("输入成功",info); }
异常报错处理
返回错误页面