本随笔记录使用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学习——统一异常处理的更多相关文章

  1. 基于Spring Boot的统一异常处理设计

    基于Spring Boot的统一异常处理设计 作者: Grey 原文地址:https://www.cnblogs.com/greyzeng/p/11733327.html Spring Boot中,支 ...

  2. spring boot配置统一异常处理

    基于@ControllerAdvice的统一异常处理 >.这里ServerException是我自定义的异常,和普通Exception分开处理 >.这里的RequestResult是我自定 ...

  3. spring boot 中统一异常处理

    基于 spring boot 对异常处理的不友好,现在通过其他的方式来统一处理异常 步骤一:自定义异常类 public class UserNotExistException extends Runt ...

  4. 基于spring boot的统一异常处理

    一.springboot的默认异常处理 Spring Boot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到该请求中处理,并且该请求有一个全局的错误页面用来展示异常内容. 例如这里我 ...

  5. Spring Boot实践——统一异常处理

    注解说明 @ControllerAdvice,是Spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强.让我们先看看@ControllerAdvice的实现: /** * Special ...

  6. 【Spring Boot】Spring Boot之统一异常处理

    一.统一异常处理的作用 在web应用中,请求处理时,出现异常是非常常见的.所以当应用出现各类异常时,进行异常的统一捕获或者二次处理(比如空指针异常或sql异常正常是不能外抛)是非常必要的,然后右统一异 ...

  7. spring boot 2 统一异常处理

    spring mvc 针对controller层异常统一处理非常简单,使用 @RestControllerAdvice 或 @RestControllerAdvice 注解就可以轻@RestContr ...

  8. Spring Boot学习路线

    Spring Boot 学习路线,本文计划根据作者近几年的工作.学习经验,来分析和制定一个学习使用 Spring Boot技术的步骤路线图. SpringBoot是伴随着Spring4.0诞生的: S ...

  9. 15 个优秀开源的 Spring Boot 学习项目,一网打尽!

    Spring Boot 算是目前 Java 领域最火的技术栈了,松哥年初出版的 <Spring Boot + Vue 全栈开发实战>迄今为止已经加印了 8 次,Spring Boot 的受 ...

随机推荐

  1. 使用U盘给笔记本重做系统

    **一.戴尔 Vostro 14 3000 Series **1. 开机时快速按F12进入BIOS界面 **2. 按照下图进行一系列的处理,把U盘被设置为第一启动项 **3. 插入U盘后进入老毛桃PE ...

  2. 【Python】剑指offer 14:剪绳子

    题目:给你一根长度为n的绳子,请把绳子剪成m段 (m和n都是整数,n>1并且m>1)每段绳子的长度记为k[0],k[1],-,k[m].请问k[0]k[1]-*k[m]可能的最大乘积是多少 ...

  3. 51nod_1255字典序最小的子序列

    作为贪心算法的某道例题,赶脚药丸啊..这么简单的代码重构第三遍才过... 首先是贪心算法思想, 1,证明贪心算法有效性:贪心策略,使用栈结构实现,遍历输入串中所有元素,对于某个元素有如下两种情况: 情 ...

  4. 笔记-python-tutorial-5.data structure

    笔记-python-tutorial-5.data structure 1.      data structure 1.1.    list operation list.append(x) #尾部 ...

  5. Unity 与Mono和.Net的关系

    一.分析 首先,我们要知道Unity,Mono,.Net 三者的关系.需要简单说一下.Net. .Net拥有跨语言,跨平台性. 跨语言:就是只要是面向.Net平台的编程语言,用其中一种语言编写的类型就 ...

  6. Redis实现之数据库(三)

    过期键删除策略 在Redis实现之数据库(二)一小节中,我们知道了数据库键的过期时间都保存在过期字典中,又知道了如果根据过期时间去判断一个键是否过期,现在剩下的问题是:如果一个键过期了,那么它什么时候 ...

  7. idea 占用内存优化调整

      idea 占用内存优化调整 https://www.cnblogs.com/metoy/p/5967696.html   https://blog.csdn.net/zdxxinlang/arti ...

  8. 使用 Bullet,BulletManager 在 XNA 中创建子弹攻击目标(十五)

    平方已经开发了一些 Windows Phone 上的一些游戏,算不上什么技术大牛.在这里分享一下经验,仅为了和各位朋友交流经验.平方会逐步将自己编写的类上传到托管项目中,没有什么好名字,就叫 WPXN ...

  9. ArrayList以及Map小练

    ArrayList常用方法 public static void main(String[] args) { List list = new ArrayList(); List list1 = new ...

  10. 【LoadRunner】loadrunner常见问题汇总

    LoadRunner常见问题1.LR 脚本为空的解决方法: 1.去掉ie设置中的第三方支持取消掉 2.在系统属性-高级-性能-数据执行保护中,添加loadrunner安装目录中的vugen.exe文件 ...