前言:异常大体分成两种:已知异常、未知异常
一、已知异常:
例如:用户名或密码错误,导致的登陆异常
二、未知异常:
例如:,输入框限制只能输入number, 但输入了文字、导致的数据类型错误,还有空指针、数组越界 等等。通常这些错误我们如果没考虑到就可能会导致系统崩溃、无法继续执行。
如何处理:
例如用户登陆,我们利用AOP(面向切面),判断用户名、密码是否正确
1、声明状态码:
public class StatusCode(){
public final static String BUSS_NO_LOGIN = "10101";//未登录
public final static String DEAL_FAIL_MSG_NO_LOGINID = "00202";// 没有登录账号或密码
public final static String DEAL_FAIL_MSG_PASS_ERR = "00203"; // 密码错误
}
2、自定义异常信息(已知异常)
/** * PFT通用型异常 * @author Administrator * */ public class PFTException extends RuntimeException {
private static final long serialVersionUID = -1977245837696067325L;
private String statusCode; public PFTException(String message) { super(message); } public PFTException(String message, Throwable cause) { super(message, cause); } public PFTException(String statusCode, String message) { super(message); this.statusCode=statusCode; } public PFTException(String statusCode, String message, Throwable cause) { super(message,cause); this.statusCode=statusCode; }
public String getStatusCode() { return statusCode; }
public void setStatusCode(String statusCode) { this.statusCode = statusCode; } public static PFTException build(String statusCode){ return new PFTException(statusCode, StatusCode.getErrorMessage(statusCode)); } }
3、利用aop我们对用户每次对后台的请求进行验证,如果用户名密码不存在或过期抛出 PFTException
/** * 检查是否已经登录,未登录时抛出 */ public void checkLogin() {
if (getCurrentUser()==null){ throw PFTException.build(StatusCode.BUSS_NO_LOGIN); } } 4、我们已经把异常抛出了,还没有进行处理,我们可以在Controller 这一层统一进行处理
①、这里我们也以写一个基类、来处理异常,其他Controller继承该类
②、我们需要借用Spring注解 :@ExceptionHandler :统一处理某一类异常,从而能够减少代码重复率和复杂度
public class BaseController {
private static Logger logger = LoggerFactory .getLogger(BaseController.class);
/** * 处理service层抛出的异常 * * @param */ @ExceptionHandler(PFTException.class) //这里是处理我们自定义的异常 @ResponseBody public WebStoreBean handlerServiceException( PFTException pftException) { logger.error("发生了{}类型的异常,异常信息为:{}", pftException.getClass(), pftException.getMessage()); return WebStoreBean.fail(pftException.getStatusCode()); }
/** * 处理未知异常 * * @param exception * @return */ @ExceptionHandler(Exception.class) @ResponseBody public WebStoreBean handlerException(Exception exception) { logger.error("发生了{}类型的异常,异常信息为:{}", exception.getClass(), exception.getMessage()); return WebStoreBean.unknown(exception.getMessage()); }
public String escapeURI(String s){ try { return java.net.URLDecoder.decode(s,"UTF-8"); } catch (UnsupportedEncodingException e) { return null; } } }
这样,发生异常信息后,将由BaseController来统一处理
|