本随笔记录使用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. jupyter notebook(二)——修改jupyter打开默认的工作目录

    1.简述 jupyter notebook,启动后,浏览器发现工作目录并不是自己真正的代码的工作路径.所以需要设置一下.这样方便自己快捷使用. 2.设置修改jupyter notebook打开后默认工 ...

  2. HDU 4857

    HDU 4857 (反向拓扑排序 + 优先队列) 糟糕的事情发生啦,现在大家都忙着逃命.但是逃命的通道很窄,大家只能排成一行. 现在有n个人,从1标号到n.同时有一些奇怪的约束条件,每个都形如:a必须 ...

  3. 批量导出ppt中内嵌的图片

    某个ppt中很多页,然后插入了很多图片,且图片都是被压缩的,看起来非常费劲,所以想着一次性把图片另存为,找了接近一个小时,终于被我找到啦,分享给大家: 1.直接把ppt的后缀修改为rar 2.解压ra ...

  4. 【01】《html5权威指南》(扫描版)(全)

    [01]<html5权威指南>(扫描版)(全) []魔芋:无高清电子书.   只看第五部分,高级功能. 作者:(美)弗里曼 著,谢延晟,牛化成,刘美英 译 [美]adam freeman ...

  5. SXCPC2018 nucoj2007 和Mengjiji一起攻克难关

    problem #include <algorithm> #include <iostream> #include <cstdio> using namespace ...

  6. 设计模式之第17章-备忘录模式(Java实现)

    设计模式之第17章-备忘录模式(Java实现) 好男人就是我,我就是曾小贤.最近陈赫和张子萱事件闹得那是一个沸沸扬扬.想想曾经每年都有爱情公寓陪伴的我现如今过年没有了爱情公寓总是感觉缺少点什么.不知道 ...

  7. MoveWindow() SetWindowPos()的区别与联系

    敲代码时,突然发现有一个背景图片无法显示,百思不得其解,最终发现是MoveWindow() SetWindowPos()这两个函数的使用不当造成的. 这里把这两个函数的前世今生给分析一下. 先看Mov ...

  8. jquery实现轮播插件

    这几天用jquery写了两个轮播的插件,功能很简单.第一次尝试写插件,有很多不足的地方,代码如下: 注:图片链接请替换掉,配置信息必须加上图片width和height. <!DOCTYPE ht ...

  9. Halcon18 Mac os 下载

    Halcon18 Mac os 下载地址:http://www.211xun.com/download_page_15.html HALCON 18 是一套机器视觉图像处理库,由一千多个算子以及底层的 ...

  10. 聊聊、RabbitMQ 第一篇

    (一)windows 下安装配置 开源的消息中间件有很多,各有各的优缺点,适合自己项目的才是最好的.首先下载 rabbitMQ 安装版本,因为 rabbitMQ 底层语言是 erlang,所以首先要先 ...