当前位置:网站首页>Have you learned the necessary global exception handler for the project
Have you learned the necessary global exception handler for the project
2022-07-01 10:01:00 【Previous year 1206】
Preface
Must be in the usual time to write the project , There must have been abnormal situations , Such as null pointer 、 Data transboundary 、 Type conversion . Every time we have to deal with this exception by ourselves , But there may be many places to deal with in a project , We can't deal with it every time , It's a lot of trouble , At this time, I must think of extracting the exception handling . Unified treatment , So our global exception handling appears .
Two things are important —— The idea of exception handling 、 The global exception is Put exception handling into a class for unified processing .
dried food
As mentioned above, the global exception is a class used to handle exceptions uniformly , So we only need a global exception handling class
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(" Global exception 1");
log.error(e.getErrorMeg(),e);
return Result.builder().data(e).build();
}
@ExceptionHandler(Exception.class)
public Result exceptionHandler(Exception e){
System.out.println(" Global exception 2");
log.error(e.getMessage(),e);
return Result.builder().data(e).build();
}
}
Be careful
- @RestControllerAdvice Yes controller enhanced , Able to intercept all SpringMVC The abnormal situation produced
- ExceptionHandler The following parameters specify which method the exception enters for processing
The following is the code for writing exceptions , Not the content of the global exception code
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," good ",200,"hh");
return result;
}
}
Running results 
This is the interception !
This is the end of the global exception interceptor , The following is based on this thing . How to integrate into the project . Construct the basic framework of a project .
- All items must be return values , First, construct the return value type of an item !
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 {
/** * The success of */
private Boolean success;
/** * Return message */
private String message;
/** * Return code */
private Integer code;
/** * Return the data */
private Object data;
/** * success * * @return */
public static Result success() {
return success(null);
}
/** * success * @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;
}
/** * Failure */
public static Result error() {
Result rb = new Result();
rb.setCode(StatusEnum.FAIL.getErrorCode());
rb.setMessage(StatusEnum.FAIL.getErrorMsg());
rb.setData(null);
return rb;
}
/** * Failure */
public static Result error( String message) {
Result rb = new Result();
rb.setCode(-1);
rb.setMessage(message);
rb.setData(null);
return rb;
}
}
The return value type is well defined , But there are many situations for the status we return , So we finally define an enumeration to list all the States , I use two here
package com.xinian.springclud_demo.enums;
import lombok.Data;
public enum StatusEnum {
SUCCESS (200," success "),
NO_PERMISSION(403, " You don't have access to "),
NO_Auth(401, " unauthorized , Please login for verification "),
NO_FOUND(404, " No resources found "),
INTERNAL_SERVER_ERROR(500, " Server exception , Please contact the Administrator !"),
FAIL(502," Failure ");
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;
}
}
If the official abnormal conditions cannot meet your requirements You can also customize exceptions .
You only need to inherit one RuntimeException That's all right. .
package com.xinian.springclud_demo.exception;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class BusinessException extends RuntimeException{
/** * Error code */
protected Integer errorCode;
/** * Error message */
protected String errorMeg;
}
Running results 
This is called global exception handling . Isn't it easy , Just need a class , That's what's called extract
Detailed code please check springboot Global exception handling
边栏推荐
- Continue to advance, and softcom power steadily promotes cloud intelligence strategy
- 我喜欢两个男人。。。
- 云原生到底是什么?它会是未来发展的趋势吗?
- PO模式深入封装
- The "China Mobile Chain" state secret engine was officially launched on BSN
- How did the data center change from "Britney Spears" to "Mrs. cow"?
- Ubuntu系统安装与配置MySQL
- [unity shader] substitution of bool type in the property definition
- 122. Thread class thread method summary; Why is the thread start method start () not run ()?
- 4hutool实战:DateUtil-格式化时间[通俗易懂]
猜你喜欢

全球基金和资管的股票建仓率达到15年内新低

谁拥有穿越周期的眼光?

架构实战营 模块九:设计电商秒杀系统

微信表情符号写入判决书,你发的OK、炸弹都可能成为“呈堂证供”

If you meet a female driver and drive didi as an amateur, you can earn 500 a day!

CSDN's one-stop cloud service is open for internal testing, and new and old users are sincerely invited to grab the fresh

一个悄然崛起的国产软件,低调又强大!

谁还在买“三只松鼠”们

TC8:UDP_ USER_ INTERFACE_ 01-08

Precautions for lvgl v8.2 string display on keil MDK (take little bear pie as an example)
随机推荐
硬件中台项目
MySQL常用命令
What is cloud primordial? Will it be the trend of future development?
预制菜迎来“黄金时代”,谁能领跑下一个万亿市场
SQL SERVER2014删除数据库失败,报错偏移量0x0000...
C# 一行代码计算文件的MD5值 - CodePlus系列
C# [字节数组]与[16进制字符串]互相转换 - CodePlus系列
BSN long story 10: how to ensure the safety of NFT
那个程序员,被打了。
项目必用的全局异常处理器,你学会了吗
It is interesting to understand MMAP in this way!
渗透常用工具-Goby
好高的佣金,《新程序员》合伙人计划来袭,人人皆可参与!
Dotnet console uses microsoft Maui. Getting started with graphics and skia
Project procurement management
Live broadcast management project
The market is relatively weak recently
[unity shader] substitution of bool type in the property definition
奇怪,为什么ArrayList初始化容量大小为10?
持续进阶,软通动力稳步推动云智能战略