实验报告1-Spring Boot自定义异常处理(1)
实验报告1-Spring Boot自定义异常处理(2)
资源下载
一、实现思路
实现根据员工id删除员工对象的功能。
要求:1、处理Exception异常。
2、处理自定义的MyException异常。
3、处理404异常。
二、实验步骤
新建maven项目,引入pom依赖,定义SpringBoots入口函数
1、处理Exception异常
(1)新建Employee Controller
controller包,EmployeeController.java
@RestController
@RequestMapping("/employee")
public class EmployeeController {@RequestMapping("/deleteOneById/{id}")public String deleteOneById(@PathVariable Integer id){System.out.println("id = "+id);return "OK";}
}
(2)定义返回结果包装类Result
util包,Result.java
public class Result<T> {private Integer status;//返回状态值private String msg;//返回信息private T data;//传送的数据private static final Integer OK_CODE=200;private static final String OK_MSG="SUCCESS";private static final Integer ERROR_CODE=0;private static final String ERROR_MSG="ERROR";public Result(Integer status, String msg, T data) {this.status = status;this.msg = msg;this.data = data;}public Result(Integer status, String msg) {this.status = status;this.msg = msg;}public Result() {this(OK_CODE, OK_MSG);}public static <T> Result<T> success(){return new Result<T>();}
public static <T> Result<T> success(T result){Result<T> response = new Result<T>();response.setData(result);return response;}public static <T> Result<T> error() {return new Result<T>(ERROR_CODE, ERROR_MSG);}public static <T> Result<T> error(Integer code, String msg) {return new Result<T>(code, msg);}public void setErrorCode() {this.status = ERROR_CODE;}//Get,Set,ToString方法
}
(3)新建异常处理类
handler包,MyExceptionHandler.java
@ControllerAdvice
public class MyExceptionHandler {@ExceptionHandler(Exception.class)@ResponseBodypublic Result hanldeException(Exception exception){return new Result(0,exception.getMessage());}
}
2、处理MyException异常
(1)定义异常信息枚举ErrorEnum
exception包,ErrorEnum.java
public enum ErrorEnum {//400系列BAD_REQUEST(400,"请求的数据格式不符!"),UNAUTHORIZED(401,"登录凭证过期!"),FORBIDDEN(403,"抱歉,你无权限访问!"),NOT_FOUND(404, "请求的资源找不到!"),//500系列INTERNAL_SERVER_ERROR(500, "服务器内部错误!"),SERVICE_UNAVAILABLE(503,"服务器正忙,请稍后再试!"),//未知异常UNKNOWN(10000,"未知异常!");private Integer code;private String message;ErrorEnum(Integer code, String message) {this.code = code;this.message = message;}public Integer getCode() {return code;}public String getMessage() {return message;}
}
(2)新建自定义异常类
exception包,MyException.java
public class MyException extends Exception{private final Integer code;private final String message;public MyException(Integer code, String message) {this.code = code;this.message = message;}public MyException(ErrorEnum errorEnum) {this(errorEnum.getCode(),errorEnum.getMessage());}public Integer getCode() {return code;}@Overridepublic String getMessage() {return message;}
}
(3)新建异常处理类
handler包,MyExceptionHandler.java
@ControllerAdvice
public class MyExceptionHandler {@ExceptionHandler(MyException.class)@ResponseBodypublic Result hanldeMyException(MyException myException){return new Result(myException.getCode(), myException.getMessage());}
}
(4)新建Employee Service
service包,EmployeeService.java
@Service
public class EmployeeService {public void deleteOne(Integer id) throws MyException {if (id < 1){//数据校验失败,抛出自定义异常throw new MyException(ErrorEnum.BAD_VERIFY);} //执行删除逻辑}
}
(5)完善Employee Controller
controller包,EmployeeController.java
@RestController
@RequestMapping("/employee")
public class EmployeeController {@Autowiredprivate EmployeeService employeeService;@RequestMapping("/deleteOne/{id}")public Result deleteOne(@PathVariable Integer id) throws MyException {Result result = new Result();employeeService.deleteOne(id); return result;}
}
3、处理404异常
(1)修改配置文件
resources目录,application.yml,启用默认的错误处理页面
# 启用默认的错误处理页面
server:error:whitelabel:enabled: false
(2)新建Employee MyErrorController
controller包,MyErrorController.java,实现ErrorController接口
@Controller
public class MyErrorController implements ErrorController {@RequestMapping("/error")@ResponseBodypublic String handleError() {return "404, 请求的资源不见了";}
}