Spring Boot学习——统一异常处理
本随笔记录使用Spring Boot统一处理异常。
本文实例是从数据库中根据ID查询学生信息,要求学生的年龄在14——20岁之间。小于14岁,提示“你可能在上初中”;大于20岁,提示“呢可能在上大学”。
第一步,创建枚举类ResultEnum,用来管理异常信息
package *;//自己定义
public enum ResultEnum {
UNKONW_ERROR(-1, "未知错误"),
SUCCESS(0, "成功"),
PRIMARY_SCHOOL(100, "年龄小于14岁,可能正在上中学"),
UNIVERSITY(101, "年龄大于20岁,可能正在上大学");
private Integer code;
private String msg;
ResultEnum( Integer code, String msg){
this.code = code;
this.msg = msg;
}
public Integer getCode(){
return this.code;
}
public String getMsg(){
return this.msg;
}
}
第二步,创建自己的异常类StudentException,代码如下:
package *;//自己定义
import *.ResultEnum; //自己定义路径
public class StudentException extends RuntimeException {
private Integer code;
public StudentException(ResultEnum resultEnum){
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
}
public void setCode(Integer code) {
this.code = code;
}
public Integer getCode() {
return code;
}
}
第三步,创建返回报文实体类Result.java
package *;//自己定义 import *.Result; //自己定义的路径 /**
* HTTP请求返回处理工具类
*/
public class ResultUtil {
public static Result success(){
return success(null);
}
public static Result success(Object object){
Result result = new Result();
result.setCode(0);
result.setMsg("成功");
result.setDate(object);
return result;
} public static Result error(Integer code, String msg){
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
第四步,创建请求返回工具类ResultUtil.java
package *;//自己定义 import *.Result;//自己定义的路径 /**
* HTTP请求返回处理工具类
*/
public class ResultUtil {
public static Result success(){
return success(null);
}
public static Result success(Object object){
Result result = new Result();
result.setCode(0);
result.setMsg("成功");
result.setDate(object);
return result;
} public static Result error(Integer code, String msg){
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
}
第五步,创建统一处理异常的类ExceptionHandle.java,代码如下:
package *; //自己定义 import *.StudentException; //自己定义路径
import *.Result; //自己定义路径
import *.ResultUtil; //自己定义路径
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice
public class ExceptionHandle {
private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class); @ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handler( Exception e){
if( e instanceof StudentException){
StudentException studentException = (StudentException) e;
return ResultUtil.error( studentException.getCode(), studentException.getMessage());
}else {
logger.info("[系统异常] {}",e);
return ResultUtil.error( -1, "未知错误");
}
}
}
第六步,在service中编写业务逻辑代码:
package *; //自己定义 import *.ResultEnum; //自己定义的路径
import *.StudentException; //自己定义的路径
import *.StudentRepository; //自己定义的路径
import *.Student; //自己定义的路径
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import javax.transaction.Transactional; @Service
public class StudentService {
@Autowired
private StudentRepository studentRepository; /**
* 根据ID查询符合条件的学生
* @param id
* @throws Exception
*/
public Student getStudentById( Integer id) throws Exception{
Student student = studentRepository.findOne(id);
Integer age = student.getAge();
if(age < 14){
throw new StudentException(ResultEnum.PRIMARY_SCHOOL);
}else if(age > 20){
throw new StudentException(ResultEnum.UNIVERSITY);
} //进行下面逻辑操作
return student;
}
}
第七步,在controller中调用service方法,代码如下:
package *; //自己定义路径 import *.Result; //自己定义路径
import *.StudentService; //自己定义路径
import *.ResultUtil; //自己定义路径
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*; import javax.validation.Valid;
import java.util.List; @RestController
public class StudentController {
@Autowired
private StudentService studentService; /**
* 根据ID查询学生
*/
@GetMapping(value = "/student/getage/{id}")
public Result getStudentById(@PathVariable("id") Integer id) throws Exception{
return ResultUtil.success(studentService.getStudentById(id));
} }
最后,使用postman访问http://127.0.0.1:8080/student/getage/1 ,查看结果。
Spring Boot学习——统一异常处理的更多相关文章
- 基于Spring Boot的统一异常处理设计
基于Spring Boot的统一异常处理设计 作者: Grey 原文地址:https://www.cnblogs.com/greyzeng/p/11733327.html Spring Boot中,支 ...
- spring boot配置统一异常处理
基于@ControllerAdvice的统一异常处理 >.这里ServerException是我自定义的异常,和普通Exception分开处理 >.这里的RequestResult是我自定 ...
- spring boot 中统一异常处理
基于 spring boot 对异常处理的不友好,现在通过其他的方式来统一处理异常 步骤一:自定义异常类 public class UserNotExistException extends Runt ...
- 基于spring boot的统一异常处理
一.springboot的默认异常处理 Spring Boot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局的错误页面用来展示异常内容. 例如这里我 ...
- Spring Boot实践——统一异常处理
注解说明 @ControllerAdvice,是Spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强.让我们先看看@ControllerAdvice的实现: /** * Special ...
- 【Spring Boot】Spring Boot之统一异常处理
一.统一异常处理的作用 在web应用中,请求处理时,出现异常是非常常见的.所以当应用出现各类异常时,进行异常的统一捕获或者二次处理(比如空指针异常或sql异常正常是不能外抛)是非常必要的,然后右统一异 ...
- spring boot 2 统一异常处理
spring mvc 针对controller层异常统一处理非常简单,使用 @RestControllerAdvice 或 @RestControllerAdvice 注解就可以轻@RestContr ...
- Spring Boot学习路线
Spring Boot 学习路线,本文计划根据作者近几年的工作.学习经验,来分析和制定一个学习使用 Spring Boot技术的步骤路线图. SpringBoot是伴随着Spring4.0诞生的: S ...
- 15 个优秀开源的 Spring Boot 学习项目,一网打尽!
Spring Boot 算是目前 Java 领域最火的技术栈了,松哥年初出版的 <Spring Boot + Vue 全栈开发实战>迄今为止已经加印了 8 次,Spring Boot 的受 ...
随机推荐
- UVA_1025 a Spy in the Metro 有向无环图的动态规划问题
应当认为,有向无环图上的动态规划问题是动态规划的基本模型之一,对于某个模型,如果可以转换为某一有向无环图的最长.最短路径问题,则可以套用动态规划若干方法解决. 原题参见刘汝佳紫薯267页. 在这个题目 ...
- Python高级主题:Python ABC(抽象基类)
#抽象类实例 作用统一规范接口,降低使用复杂度.import abcclass Animal(metaclass = abc.ABCMeta): ##只能被继承,不能实例化,实例化会报错 @abc.a ...
- P2920 [USACO08NOV]时间管理Time Management
P2920 [USACO08NOV]时间管理Time Management 题目描述 Ever the maturing businessman, Farmer John realizes that ...
- JSP自定义tag控件标签
JSP支持自定tag的方法,那就是直接讲JSP代码保存成*.tag或者*.tagx的标签定义文件.tag和tagx文件不仅支持经典jsp代码,各种标签模版代码,还支持xml样式的jsp指令代码. 按照 ...
- 微信SSL证书更换的检查与安装方法
Ubuntu, Debian 查看根证书 确认操作系统上,是否存在以下文件: /etc/ssl/certs/DigiCert_Global_Root_CA.pem /etc/ssl/certs/Bal ...
- 码农与UI沟通的日常
事情是这样的,这是一个兴趣群组的效果图. 我看了一眼没有帖子时的提示,觉得这样的提示 不走心 不能展现出我们团队对于人生及世界的深度理解和高尚的品格. 于是,我选择了表达内心的真实感受. 我觉得这完美 ...
- STL学习笔记5--map and multimap
Maps是一种关联式容器,包含“关键字/值”对. Multimaps和maps很相似,但是MultiMaps允许重复的元素. 简单介绍: 1.声明,首先包含头文件 “map” map <int, ...
- _cdecl _stdcall
__cdecl程序的压栈方式为C风格__stdcall为PASCAL风格 举个例子:(1) C函数 Fun1(a,b,c) 函数调用时,参数压栈顺序为 c , b , a(2) PASC ...
- C++ STL map容器的说明测试1
// maptest.cpp : 定义控制台应用程序的入口点.// #include "stdafx.h" /*********************************** ...
- Bootstrap从入门到放弃
简要介绍 Bootstrap,以及如何下载.使用,还有基本模版和案例,等等. https://v3.bootcss.com/getting-started/#template