SpringBoot配置全局異常處理

一蛤虐、環(huán)境

  • jdk1.8
  • idea2018.2.2
  • maven3.5.3
  • mybatsi-plus3.4.1
  • mysql5.7

二、項目配置

  • pom文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.yxl</groupId>
    <artifactId>yxl</artifactId>
    <packaging>pom</packaging>
    <version>1.0.0</version>
    <modules>
        <module>yxl_project01</module>
    </modules>
    <name>yxl</name>
    <description>公共項目</description>

    <properties>
        <druid-version>1.2.6</druid-version>
        <mybatis-plus-version>3.4.1</mybatis-plus-version>
        <mysql-connector-version>8.0.23</mysql-connector-version>
        <lombok-version>1.18.18</lombok-version>
        <hutool-version>5.6.5</hutool-version>
        <httpcore-version>4.4.12</httpcore-version>

    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>2.5.6</version>
                <scope>import</scope>
                <type>pom</type>
            </dependency>

            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>${druid-version}</version>
            </dependency>

            <dependency>
                <groupId>com.baomidou</groupId>
                <artifactId>mybatis-plus-boot-starter</artifactId>
                <version>${mybatis-plus-version}</version>
            </dependency>

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>${mysql-connector-version}</version>
            </dependency>

            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>${lombok-version}</version>
            </dependency>

            <dependency>
                <groupId>cn.hutool</groupId>
                <artifactId>hutool-all</artifactId>
                <version>${hutool-version}</version>
            </dependency>

            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpcore</artifactId>
                <version>${httpcore-version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>
  • 統(tǒng)一返回結(jié)果
package com.yxl.common.util;

import org.apache.http.HttpStatus;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname R
 * @Description TODO
 * @Date 2021-12-20 17:19
 * @Created by yxl
 */
public class R extends HashMap<String,Object> {
    private static final long serialVersionUID = 1L;

    public R(){
        put("code",0);
        put("msg","success");
    }

    public static R error() {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知異常肝陪,請聯(lián)系管理員");
    }

    public static R error(String msg) {
        return error(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
    }

    public static R error(int code, String msg) {
        R r = new R();
        r.put("code", code);
        r.put("msg", msg);
        return r;
    }

    public static R ok(String msg) {
        R r = new R();
        r.put("msg", msg);
        return r;
    }

    public static R ok(Map<String, Object> map) {
        R r = new R();
        r.putAll(map);
        return r;
    }

    public static R ok() {
        return new R();
    }

    public R put(String key, Object value) {
        super.put(key, value);
        return this;
    }
}
  • controller
package com.yxl.project01.controller;

import com.yxl.common.util.R;
import com.yxl.project01.entity.User;
import com.yxl.project01.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Classname UserController
 * @Description TODO
 * @Date 2021-12-20 17:14
 * @Created by yxl
 */
@RestController
@RequestMapping("/user")
public class UserController {

}
  • dao
package com.yxl.project01.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.yxl.project01.entity.User;
import org.apache.ibatis.annotations.Mapper;

/**
 * @Classname UserMapper
 * @Description TODO
 * @Date 2021-12-20 17:10
 * @Created by yxl
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {

}
  • entity
package com.yxl.project01.entity;

import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

import java.util.Date;

/**
 * @Classname User
 * @Description TODO
 * @Date 2021-12-20 17:07
 * @Created by yxl
 */
@Data
@TableName("tb_user")
public class User {

    @TableId
    private Long id;

    private String name;

    private Integer age;

    private Date birthday;

    private String icon;

    private Integer status;

    private String description;
}
  • service
package com.yxl.project01.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.yxl.project01.entity.User;

/**
 * @Classname UserService
 * @Description TODO
 * @Date 2021-12-20 17:11
 * @Created by yxl
 */
public interface UserService extends IService<User> {

}
  • serviceImpl
package com.yxl.project01.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxl.project01.dao.UserMapper;
import com.yxl.project01.entity.User;
import com.yxl.project01.service.UserService;
import org.springframework.stereotype.Service;

/**
 * @Classname UserServiceImpl
 * @Description TODO
 * @Date 2021-12-20 17:12
 * @Created by yxl
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
}
  • 啟動類
package com.yxl.project01;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Classname yxlProject01Application
 * @Description TODO
 * @Date 2021-12-20 17:03
 * @Created by yxl
 */
@SpringBootApplication
@MapperScan("com.yxl.project01.dao")
public class yxlProject01Application {

    public static void main(String[] args) {
        SpringApplication.run(yxlProject01Application.class,args);
    }
}

三驳庭、全局異常處理配置

1.首先在controller中創(chuàng)建一個方法getException(),制造一個異常

import com.yxl.project01.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @Classname UserController
 * @Description TODO
 * @Date 2021-12-20 17:14
 * @Created by yxl
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @GetMapping("/getException")
    public R getException(){
        int a = 10;
        int b = 0;
        System.out.println(a/b);
        return R.ok();
    }
}

2.重啟服務(wù)器

3.訪問此url后,在控制臺出現(xiàn)如下異常

java.lang.ArithmeticException: / by zero
    at com.yxl.project01.controller.UserController.getException(UserController.java:23) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_181]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_181]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_181]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) ~[spring-web-5.3.12.jar:5.3.12]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:150) ~[spring-web-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:117) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1067) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) ~[tomcat-embed-core-9.0.54.jar:4.0.FR]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.3.12.jar:5.3.12]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) ~[tomcat-embed-core-9.0.54.jar:4.0.FR]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.3.12.jar:5.3.12]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.12.jar:5.3.12]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.3.12.jar:5.3.12]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.12.jar:5.3.12]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.3.12.jar:5.3.12]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.3.12.jar:5.3.12]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) ~[tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) [tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540) [tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) [tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) [tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) [tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) [tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895) [tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722) [tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) [tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) [tomcat-embed-core-9.0.54.jar:9.0.54]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.54.jar:9.0.54]
    at java.lang.Thread.run(Thread.java:748) [na:1.8.0_181]

此異常為算術(shù)異常:即除數(shù)不能為0,當我們使用前后端分離開發(fā)的時候氯窍,需要返回給前端統(tǒng)一格式的結(jié)果饲常,那我們就需要用到全局異常處理,并自定義異常返回結(jié)果了狼讨。

4.定義全局異常處理

1.新增GlobalExceptionHandler.class類并添加如下配置

package com.yxl.project01.exception;

import com.yxl.common.util.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname GlobalExceptionHandler
 * @Description TODO
 * @Date 2021-12-22 11:13
 * @Created by yxl
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)
    public R arithmeticExceptionHandler(ArithmeticException e){
        return R.error(10001,e.getMessage());
    }
}

@RestControllerAdvice:將該類標記為全局異常處理類不皆。
@ExceptionHandler(ArithmeticException.class):標記在方法上表示該方法捕獲哪些異常,小括號的形參就是要捕獲的異常類

我們使用{}Postman再次請求url熊楼,結(jié)果如下圖:

idea控制臺也沒有錯誤信息了,如下:

2.為了統(tǒng)一聲明管理狀態(tài)碼和返回消息,我們可以聲明一個枚舉類BizCodeEnume.class專門來管理鲫骗,如下:

package com.yxl.common.exception;

/**
 * @Classname BizCodeEnum
 * @Description TODO
 * @Date 2021-12-22 11:29
 * @Created by yxl
 */
public enum BizCodeEnum {

    UNKNOW_EXCEPTION(10000,"系統(tǒng)未知異常"),
    ARITHMETIC_EXCEPTION(10001,"算術(shù)異常"),;
    
    private int code;
    private String msg;

    private BizCodeEnum(int code,String msg){
        this.code = code;
        this.msg = msg;
    }

    public int getCode(){
        return code;
    }

    public String getMsg(){
        return msg;
    }
}

3犬耻、修改全局異常處理方法中的代碼

package com.yxl.project01.exception;

import com.yxl.common.exception.BizCodeEnume;
import com.yxl.common.util.R;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @Classname GlobalExceptionHandler
 * @Description TODO
 * @Date 2021-12-22 11:13
 * @Created by yxl
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ArithmeticException.class)
    public R arithmeticExceptionHandler(ArithmeticException e){
        return R.error(BizCodeEnume.ARITHMETIC_EXCEPTION.getCode(),BizCodeEnume.ARITHMETIC_EXCEPTION.getMsg());
    }
}

4、重啟服務(wù)器后使用Postman訪問url执泰,結(jié)果如下:

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末枕磁,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子术吝,更是在濱河造成了極大的恐慌计济,老刑警劉巖,帶你破解...
    沈念sama閱讀 207,248評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件排苍,死亡現(xiàn)場離奇詭異沦寂,居然都是意外死亡,警方通過查閱死者的電腦和手機淘衙,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,681評論 2 381
  • 文/潘曉璐 我一進店門传藏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人彤守,你說我怎么就攤上這事毯侦。” “怎么了具垫?”我有些...
    開封第一講書人閱讀 153,443評論 0 344
  • 文/不壞的土叔 我叫張陵侈离,是天一觀的道長。 經(jīng)常有香客問我筝蚕,道長卦碾,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,475評論 1 279
  • 正文 為了忘掉前任饰及,我火速辦了婚禮蔗坯,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘燎含。我一直安慰自己宾濒,他們只是感情好,可當我...
    茶點故事閱讀 64,458評論 5 374
  • 文/花漫 我一把揭開白布屏箍。 她就那樣靜靜地躺著绘梦,像睡著了一般。 火紅的嫁衣襯著肌膚如雪赴魁。 梳的紋絲不亂的頭發(fā)上卸奉,一...
    開封第一講書人閱讀 49,185評論 1 284
  • 那天,我揣著相機與錄音颖御,去河邊找鬼榄棵。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的疹鳄。 我是一名探鬼主播拧略,決...
    沈念sama閱讀 38,451評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼瘪弓!你這毒婦竟也來了垫蛆?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,112評論 0 261
  • 序言:老撾萬榮一對情侶失蹤腺怯,失蹤者是張志新(化名)和其女友劉穎袱饭,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體呛占,經(jīng)...
    沈念sama閱讀 43,609評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡虑乖,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,083評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了栓票。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片决左。...
    茶點故事閱讀 38,163評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡走贪,死狀恐怖佛猛,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情坠狡,我是刑警寧澤继找,帶...
    沈念sama閱讀 33,803評論 4 323
  • 正文 年R本政府宣布,位于F島的核電站逃沿,受9級特大地震影響婴渡,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜凯亮,卻給世界環(huán)境...
    茶點故事閱讀 39,357評論 3 307
  • 文/蒙蒙 一边臼、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧假消,春花似錦柠并、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,357評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至啃沪,卻和暖如春粘拾,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背创千。 一陣腳步聲響...
    開封第一講書人閱讀 31,590評論 1 261
  • 我被黑心中介騙來泰國打工缰雇, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留入偷,地道東北人。 一個月前我還...
    沈念sama閱讀 45,636評論 2 355
  • 正文 我出身青樓械哟,卻偏偏與公主長得像盯串,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子戒良,可洞房花燭夜當晚...
    茶點故事閱讀 42,925評論 2 344

推薦閱讀更多精彩內(nèi)容