public class MyException extends RuntimeException {
private int code;
public MyException( int code, String message ) {
super(message);
this.code = code;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
创建自定义异常类原因:java自己的异常类只有message参数,这里我们还需要一个code参数(用来记录请求状态)。并且创建自定义异常还能和系统异常区分开来。
public class Result implements Serializable {
private int code;
private String msg;
private Object data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
}
@ControllerAdvice
public class MyExceptionHandle {
private static final Logger logger = LoggerFactory.getLogger(MyExceptionHandle.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e) {
if(e instanceof MyException) {
MyException myException = (MyException)e;
return ResultUtil.error(myException.getCode(),myException.getMessage());
}else{
logger.error("系统异常",e);
return ResultUtil.error(ResultEnum.UNKNOWN_ERROR.getCode(),ResultEnum.UNKNOWN_ERROR.getMsg());
}
}
}
ResultEnum.java:作用:规范错误码code极其具体表示含义。方便维护。
public enum ResultEnum {
UNKNOWN_ERROR(500,"未知错误"),
SUCCESS(200,"操作成功"),
ERROR_1(111,"未成年1"),
ERROR_2(112,"未成年2");
private int code;
private String msg;
ResultEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
ResultUtil.java:作用:方便生成Result.java而已
public class ResultUtil {
public static Result error(int code,String msg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
result.setData(null);
return result;
}
public static Result success(Object obj) {
Result result = new Result();
result.setCode(200);
result.setMsg("成功");
result.setData(obj);
return result;
}
public static Result success() {
Result result = new Result();
result.setCode(200);
result.setMsg("成功");
result.setData(null);
return result;
}
}
HelloController.java
@RestController
public class HelloController {
@GetMapping("/aa")
public Result aa(Girl girl) throws Exception {
if(girl.getId() < 18) {
throw new MyException(ResultEnum.ERROR_1.getCode(),ResultEnum.ERROR_1.getMsg());
}else if(girl.getId() < 20) {
throw new MyException(ResultEnum.ERROR_2.getCode(),ResultEnum.ERROR_2.getMsg());
}
return ResultUtil.success("aaa");
}
}
1.@RestController:等价于@Controller 、@ResponseBody一起使用
2.@ControllerAdvice:主要和@ExceptionHandler配合使用,来配置全局异常处理器,另外@ControllerAdvice内部使用了@Component注解,因此会自动被spring容器加载。如图:
3.自定义异常需要继承RuntimeException异常类,否则spring不会对事务进行回滚。全局异常处理器配置核心就是上面的注解。主要作用是为了将程序中可能出现的异常情况自己抛出然后用通用的格式显示。以便正确的处理错误。另外,代码如果想要优化就立马优化,如果说以后优化基本就等于永远不不会优化了。