当前位置:网站首页>项目必用的全局异常处理器,你学会了吗
项目必用的全局异常处理器,你学会了吗
2022-07-01 09:41:00 【昔年1206】
前言
想必在平时写项目得时候,一定遇到过出现异常得情况,比如空指针啊、数据越界、类型转化什么得。每次我们都要自己去处理这个异常,但是一个项目中可能有多个需要处理得地方,我们总不能每次都处理,多费事啊,这个时候肯定想到的是将这个异常的处理抽取出来。统一的处理,所以我们的全局异常处理就出现了。
有两点很重要——异常处理的思想
、全局异常就是把异常处理放在一个类中进行统一处理
。
干货
上面说到全局异常就是一个类作为统一处理异常地方,所以我们只需要顶一个全局异常处理类就行了
package com.xinian.springclud_demo.exception;
import com.xinian.springclud_demo.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.sql.ResultSet;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(value = BusinessException.class)
public Result zdyExceptionHandeler (BusinessException e){
System.out.println("全局异常1");
log.error(e.getErrorMeg(),e);
return Result.builder().data(e).build();
}
@ExceptionHandler(Exception.class)
public Result exceptionHandler(Exception e){
System.out.println("全局异常2");
log.error(e.getMessage(),e);
return Result.builder().data(e).build();
}
}
注意点
- @RestControllerAdvice 对controller进行增强,能够拦截所有SpringMVC产生的异常情况
- ExceptionHandler 通过后面的参数指定异常情况是进入哪个方法进行处理
下面就是写异常的代码了,不是全局异常代码的内容
package com.xinian.springclud_demo.controller;
import com.xinian.springclud_demo.common.Result;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestException {
@GetMapping("/a")
public Result query(){
int i=1/0;
Result result = new Result(true,"好",200,"hh");
return result;
}
}
运行结果
这不就拦截到了嘛!
就此全局异常拦截器已经说完了,下面说的是根据这个东西。如何融入到项目当中。构造出一个项目的基础框架。
- 凡是项目肯定是返回值,首先构造一个项目的返回值类型吧!
package com.xinian.springclud_demo.common;
import com.xinian.springclud_demo.enums.StatusEnum;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Result {
/** * 是否成功 */
private Boolean success;
/** * 返回消息 */
private String message;
/** * 返回编码 */
private Integer code;
/** * 返回数据 */
private Object data;
/** * 成功 * * @return */
public static Result success() {
return success(null);
}
/** * 成功 * @param data * @return */
public static Result success(Object data) {
Result rb = new Result();
rb.setCode(StatusEnum.SUCCESS.getErrorCode());
rb.setMessage(StatusEnum.SUCCESS.getErrorMsg());
rb.setData(data);
return rb;
}
/** * 失败 */
public static Result error() {
Result rb = new Result();
rb.setCode(StatusEnum.FAIL.getErrorCode());
rb.setMessage(StatusEnum.FAIL.getErrorMsg());
rb.setData(null);
return rb;
}
/** * 失败 */
public static Result error( String message) {
Result rb = new Result();
rb.setCode(-1);
rb.setMessage(message);
rb.setData(null);
return rb;
}
}
返回值类型定义好,但是我们返回的状态其实有很多种情况的,所以我们最后定义一个枚举将所有的状态列举出来,我这里就使用了两个
package com.xinian.springclud_demo.enums;
import lombok.Data;
public enum StatusEnum {
SUCCESS (200,"成功"),
NO_PERMISSION(403, "你无权访问"),
NO_Auth(401, "未授权,请登录验证"),
NO_FOUND(404, "未找到资源"),
INTERNAL_SERVER_ERROR(500, "服务器异常, 请联系管理员!"),
FAIL(502,"失败");
private Integer errorCode;
private String errorMsg;
StatusEnum(Integer errorCode,String errorMsg){
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public Integer getErrorCode() {
return errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
}
如果官方规定的异常情况不能满足你的要求 你还可以自定义异常。
只需要你去继承一个RuntimeException就可以了。
package com.xinian.springclud_demo.exception;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BusinessException extends RuntimeException{
/** * 错误编码 */
protected Integer errorCode;
/** * 错误提示 */
protected String errorMeg;
}
运行结果
这就是所谓的全局异常处理。是不是很简单啊,只需要一个类就可以了,这就是所谓的抽取
详细代码请查看springboot全局异常处理
边栏推荐
- Solution of EPS image blur by latex insertion
- Upload labs for file upload - white box audit
- 持续进阶,软通动力稳步推动云智能战略
- Swift control encapsulation - paging controller
- Short circuit operator lazy evaluation
- Wechat applet WebView prohibits page scrolling without affecting the implementation of overflow scrolling in the business
- 项目采购管理
- Comparison between Oracle JDK and openjdk
- Computer USB, HDMI, DP various interfaces and speeds
- 硬件中台项目
猜你喜欢
Some tools used in embedded development
Precautions for lvgl v8.2 string display on keil MDK (take little bear pie as an example)
JS scope chain and closure
新数据库时代,不要只学 Oracle、MySQL
Concept of digital currency
年薪100万,在北上广深买的起房子吗?
奇怪,为什么ArrayList初始化容量大小为10?
全球基金和资管的股票建仓率达到15年内新低
电脑USB、HDMI、DP各种接口及速度
Flinkv1.13实现金融反诈骗案例
随机推荐
MapReduce programming basics
STM32逆变器电源设计方案,基于STM32F103控制器[通俗易懂]
High precision factorial
Live broadcast management project
js变量提升(hoisting)
Huawei accounts work together at multiple ends to create a better internet life
这样理解mmap,挺有意思!
Upload labs for file upload - white box audit
js原型继承仅可继承实例而非构造器
集成积木报表报错 org.apache.catalina.core.StandardContext.filterStart 启动过滤器异常
SQL learning notes (01) - basic knowledge of database
Wechat emoticons are written into the judgment, and the OK and bomb you send may become "testimony in court"
122. Thread class thread method summary; Why is the thread start method start () not run ()?
Postgraduate entrance examination vocabulary 2023 sharing (1)
121. thread scheduling: join() method and yield() method
Click the screen with your finger to simulate F11 and enter the full screen
Packetdrill script analysis guide
PHP code audit and File Inclusion Vulnerability
PO模式深入封装
Dotnet console uses microsoft Maui. Getting started with graphics and skia