本随笔记录使用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. PhotoSwipe图片展示插件

    这个插件相当棒!功能也很强大,可以自行体会. 官方网址:http://www.photoswipe.com/ github地址:https://github.com/codecomputerlove/ ...

  2. JavaScript 资源大全中文版

    我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列的资源整理.awesome-javascript 是 sorrycc 发起维护的 JS 资源列表,内容包括:包管理器.加 ...

  3. 笔记1 python入门学习笔记

    目录 官方手册 菜鸟站手册地址: python的运行方法 注释 小技巧: input()接收用户输入的内容(默认为字符串) print() 运算符 is 是判断两个标识符是不是引用自一个对象 all和 ...

  4. python flask学习第1天

    flask安装: 第一个flask程序: 用pycharm新建一个flask项目,新建项目的截图如下: app.py代码如下: #从flask这个包中导入Flask这个类 #Flask这个类是项目的核 ...

  5. Codeforces Round #459 (Div. 2)-A. Eleven

    A. Eleven time limit per test1 second memory limit per test256 megabytes Problem Description Eleven ...

  6. 在VIM 里面编辑和保存

    #查看a.sh 的内容 cat a.sh #编辑a.sh的内容 键入i,下面会出现 insert,输入内容之后按下esc会退出编辑模式(此时下面的insert没有了) 再输入:wq保存

  7. activity切换交互动画

    activity切换的时候,想要有动画,那么... 1.想要有效果的activity设置theme <activity android:name=".MainActivity" ...

  8. Spring Boot 开发系列一 开发踩坑

    这是学习spring boot 的第二周,公司号称这玩意是啥都不会的新手就可以填空开发,于是决定上手一把,怎么说我也是搞了快七八年的.NET和.NETcore,没想到无情打脸,快被这个能填空开的IDE ...

  9. 【Palindrome Number】cpp

    题目: Determine whether an integer is a palindrome. Do this without extra space. click to show spoiler ...

  10. LeetCode——Problem2:Add Two Numbers

    这又过了一周了,总感觉刷这个好花时间呀.每次都一两个小时.让我不好安排时间.应该是我太菜了.对,没错,就是这样 1.题目 You are given two non-empty linked list ...