springboot使用自定义异常
-
创建自定义异常类,继承RuntimeException
public class MyException extends RuntimeException {
private int code; //异常状态码
private String message; //异常信息
private String descinfo; //描述
/**
* @param code 状态
* @param message 信息
* @param descinfo 错误,描述!
*/
public MyException(int code, String message,String descinfo) {
this.code = code;
this.message = message;
this.descinfo = descinfo;
}
public MyException() {
}
public String getDescinfo() {
return descinfo;
}
public void setDescinfo(String descinfo) {
this.descinfo = descinfo;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
} -
创建ControllerAdvice 使用boot为我们提供的@ControllerAdvice注解和@ExceptionHandler来实现对全局异常的捕抓 返回信息为json
@ControllerAdvice //控制器增强 配合ExceptionHandler实现全局捕抓异常
@Slf4j
public class MyControllerAdvice {
@ExceptionHandler(value = MyException.class)
@ResponseBody
public Map exceptionHandler(MyException me) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("code",me.getCode());
map.put("message",me.getMessage());
//打印日志信息
log.info("捕抓到异常信息->>"+me.getDescinfo());
return map;
} -
Map<String, Object> map = new HashMap<>();
UsernamePasswordToken token = new UsernamePasswordToken(name,password);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
map.put("code",0);
map.put("message","登录成功!");
return map;
} catch (UnknownAccountException e) {//用户名不存在
throw new MyException(-1,"用户名不存在!","用户名不存在");
}catch (IncorrectCredentialsException e) {//账号或者密码不正确
throw new MyException(-1,"账号或密码错误!","账号或者密码不正确");
}catch (LockedAccountException e) {//限制登录
throw new MyException(-1,"该账号已经被限制登录请联系管理员!","该账号已经限制登录了!");
}catch (Exception e) {
throw new MyException(-1,"未知异常","登录出现了异常->>"+e.getMessage());
}
你要学会如何长大