SpringBoot註解@ControllerAdvice知多少?

2021-03-02 java1234

點擊上方藍色字體,選擇「標星公眾號」

優質文章,第一時間送達

66套java從入門到精通實戰課程分享

為了方便對異常的統一管理,spring mvc提供了ControllerAdvice註解對異常進行統一的處理,拿到這些異常信息後,可以做一些處理,比如提供一個統一的web界面查看異常信息,或者普通到異常信息後,發送簡訊、郵件形式通知到相關人員,可以幫助開發人員快速發現並定位問題,減少以往通過查看線上日誌文件排查問繁瑣鎖耗時的所耗費的時間。下面我跟大家介紹具體步驟。

配置

spring 版本:

<org.springframework-version>4.1.9.RELEASE</org.springframework-version>  

spring-servlet.xml,注意必須開啟註解,即xml要有

<?xml version="1.0" encoding="UTF-8"?>  
<beans:beans xmlns="http://www.springframework.org/schema/mvc"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"  
    xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">  

    <!-- DispatcherServlet Context: defines this servlet's request-processing   
        infrastructure -->  

    <!-- Enables the Spring MVC @Controller programming model -->  
    <annotation-driven />  

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving   
        up static resources in the ${webappRoot}/resources directory -->  
    <resources mapping="/resources/**" location="/resources/" />  

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources   
        in the /WEB-INF/views directory -->  
    <beans:bean  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <beans:property name="prefix" value="/WEB-INF/views/" />  
        <beans:property name="suffix" value=".jsp" />  
    </beans:bean>  
    <context:component-scan base-package="org.as.asjee" use-default-filters="false">  
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>  
    </context:component-scan>  

</beans:beans> 

異常統一處理類

package org.as.asjee.core.exception;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;

import org.as.asjee.core.log.AsJEELogger;
import org.as.asjee.core.log.AsJEELoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * 捕獲異常統一處理
 * @description TODO
 * @author chen.gs
 * @create date 2016年4月28日
 * @modified by 
 * @modify date
 * @version v1.0
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private final static AsJEELogger LOG = AsJEELoggerFactory.getLogger(GlobalExceptionHandler.class);

    private final static String EXPTION_MSG_KEY = "message";

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public void handleBizExp(HttpServletRequest request, Exception ex){
        LOG.info("Business exception handler  " + ex.getMessage() );
        request.getSession(true).setAttribute(EXPTION_MSG_KEY, ex.getMessage());
    }

    @ExceptionHandler(SQLException.class)
    public ModelAndView handSql(Exception ex){
        LOG.info("SQL Exception " + ex.getMessage());
        ModelAndView mv = new ModelAndView();
        mv.addObject("message", ex.getMessage());
        mv.setViewName("sql_error");
        return mv;
    }

}


自定義異常類BussinessException.java
package org.as.asjee.core.exception;

/**
 * 業務異常
 * @description TODO
 * @author chen.gs
 * @create date 2016年4月28日
 * @modified by 
 * @modify date
 * @version v1.0
 */
public class BusinessException extends Exception{

    private static final long serialVersionUID = 1L;

    //業務類型
    private String bizType;
    //業務代碼
    private int bizCode;
    //錯誤信息
    private String message;

    public BusinessException(String bizType, int bizCode, String message){
        super(message);
        this.bizType = bizType;
        this.bizCode = bizCode;
        this.message = message;
    }

    public BusinessException(String message){
        super(message);
        this.bizType = "";
        this.bizCode = -1;
        this.message = message;
    }

    public BusinessException(String bizType, String message){
        super(message);
        this.bizType = bizType;
        this.bizCode = -1;
        this.message = message;
    }

    public BusinessException(int bizCode, String message){
        super(message);
        this.bizType = "";
        this.bizCode = bizCode;
        this.message = message;
    }

    public String getBizType() {
        return bizType;
    }

    public void setBizType(String bizType) {
        this.bizType = bizType;
    }

    public int getBizCode() {
        return bizCode;
    }

    public void setBizCode(int bizCode) {
        this.bizCode = bizCode;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

controller
package org.as.asjee.core.security.web;

import java.sql.SQLException;

import javax.annotation.Resource;

import org.as.asjee.core.exception.BusinessException;
import org.as.asjee.core.security.model.User;
import org.as.asjee.core.security.service.UserService;
import org.as.asjee.core.service.ServiceFacade;
import org.as.asjee.core.web.AbstractController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/security/user")
public class UserController  extends AbstractController<User>{

    @Resource
    private UserService userService;
    @Resource
    private ServiceFacade serviceFacade;

    @RequestMapping("login")
    public String login() { 
        return "login";
    }

    @RequestMapping("login2")
    public String login2() throws Exception {
        throw new SQLException("出錯鳥。。。。。。。。。");
    }   

    @RequestMapping("login3")
    public String login3() throws Exception { 
        throw new BusinessException("業務執行異常");
    }

    //此方法拋出的異常不是由GlobalExceptionHandler處理
    //而是在catch塊處理
    @RequestMapping("login4")
    public String login4() { 
        try {
            throw new BusinessException("業務執行異常");
        } catch (BusinessException e) {
            e.printStackTrace();
        }
        return "login";
    }

}

簡要說明

在Controller中拋出的異常,當沒有被catch處理時,GlobalExceptionHandler中定義的處理方法可以起作用,在方法寫明註解@ExceptionHandler,並註明其異常類即可。此種方法不僅可以作用於Controller,同樣的在DAO層、service層也可,都可以由GlobalExceptionHandler進行處理。此種寫法減少代碼的入侵,值得推薦。 
異常的統一處理只是註解ControllerAdvice用處之一,有興趣了解更多的,請到spring官網查閱。

版權聲明:本文為博主原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處連結和本聲明。

本文連結:

https://blog.csdn.net/xiongyouqiang/article/details/80208067

粉絲福利:實戰springboot+CAS單點登錄系統視頻教程免費領取

👇👇👇

感謝點讚支持下哈 

相關焦點

  • SpringBoot開發常用的註解及作用
    隨著網際網路的快速發展,不斷的湧出新的技術,springboot是什麼呢?springboot它是spring開源組織下的子項目,主要是用來簡化spring的難度以及不足,節省程式設計師的繁重的配置,為程式設計師開發過程中各種啟動器。
  • Springboot之@RequestMapping註解
    版本:springboot:2.3.01、用途@RequestMapping註解將HTTP請求映射給controller來處理,包括返回視圖頁面的controller和Rest服務的controller。
  • Springboot @EnableWebMvc 註解
    點擊上方藍色字體,選擇「標星公眾號」優質文章,第一時間送達  作者 |  荏苒經十載來源 |  urlify.cn/yUJbqi66套java從入門到精通實戰課程分享@EnableWebMvc 註解的源碼如下
  • Spring Boot2 系列教程(十二)@ControllerAdvice 的三種使用場景
    @ControllerAdvice ,很多初學者可能都沒有聽說過這個註解,實際上,這是一個非常有用的註解,顧名思義,這是一個增強的 Controller。@ExceptionHandler 註解用來指明異常的處理類型,即如果這裡指定為 NullpointerException,則數組越界異常就不會進到這個方法中來。
  • SpringBoot 全局日期格式化(基於註解)
    作者:yizhiwazi連結:https://www.jianshu.com/p/f4654d251104學習目標快速學會通過註解 @JsonComponent自定義日期格式化的序列化器。快速查閱專題閱讀:《SpringBoot 布道系列》:https://www.jianshu.com/p/964370d9374e源碼下載:SpringBoot Date Format Anno:https://github.com/yizhiwazi/springboot-socks--- Hey Man,Don't forget to Star or Fork
  • Spring Boot 示例的@RestController 和 @RequestMapping註解
    在示例原始碼類中的第一個註解(annotation)是 @RestController。這個註解被稱為 stereotype 註解。在使用 Spring 的時候,需要對註解有所了解。Spring 有多個類型的註解,例如在包 org.springframework.context.annotation 和 org.springframework.stereotype 的註解。
  • spring和spring boot常用註解及使用
    @ResponseBody通常使用在controller方法上,作用是將方法的返回值通過合適的HttpMessageConverter轉換成特定格式寫入到response的body區域,然後返回給客戶端,如果沒有使用@RequestBody註解,方法返回值將會封裝到ModelAndView並解析返回視圖。
  • springboot如何做到接口返回JSP頁面
    環境:IDEA、java、springboot、tomcat等相關開發工具.主入口類右鍵運行,訪問頁面:http://localhost:8080/hello,結果出現該頁面  開始以為是控制器類controller
  • 使用 ControllerAdvice & ExceptionHandler 處理異常
    -- End --></body>創建 CustomExceptionHandler 接收MVC可攔截異常package com.sapphire.demo.advice;@ControllerAdvicepublic class CustomExceptionHandler
  • Springboot整合easyExcel導入導出Excel
    來源 |  urlify.cn/BFnIrq背景:最近公司有個需求要求可以導入、導出excel,因此在此記錄學習一下如何使用Springboot整合easyExcel;需求:資料庫中有張user表,有個業務要求可以導入、導出「用戶名單.xls」表一、準備:創建項目:關於springboot
  • SpringBoot-Condition
    springboot中提供了一系列@Condition* 註解來處理有條件注入的情況。1. 說明Spring4中增加了@Condition annotation, 使用該Annotation之後,在做依賴注入的時候,會檢測是否滿足某個條件來決定是否注入某個類。
  • advice的用法知多少
    今天我們分享advice的用法總結advice[U]勸告、忠告、建議advice前可用some, much, a piece of等來修飾,不可用an, many及數詞等,advice後面不可加s。常見搭配:ask for one’s advice = ask advice of sb. 徵求某人的意見give sb. advice on…關於……對某人提出忠告take / follow advice接受意見。
  • spring security 整合 springboot 入門案例
    這一節我們來學習一下 spring security 與 springboot 整合,為了力求簡單,此處不演示資料庫相關操作。plugin>    </plugins></build>目錄結構整體目錄結構如下:│  Application.java│├─config│      MyPasswordEncoder.java│      WebSecurityConfig.java│├─controller
  • springboot整合redis簡單案例
    前言:這裡簡單介紹下springboot整合redis(window版),以及簡單的測試demo。根據當前自己電腦的系統下載對應的redis版本,我這裡是以window版本作為測試的 demo。下載完直接解壓到自定義的目錄,如下:雙擊運行redis-server.exe,如下說明redis啟動成功:在創建的springboot項目的配置文件中,配置如下:創建配置類:
  • Springboot+MybatisPlus高效實現增刪改查
    的依賴:提供了使用springboot的能力。entity實體類:對應資料庫中的表的實體類,有各種Mybatis-plus的註解可以使用,比如主鍵生成策略、邏輯刪除、自動填充等。xml文件:Mybatis的sql配置文件,對應Mapper接口。Mapper接口:就是我們平常所說的Dao層暴露的方法所在接口,接口中的方法對應xml文件中對應的sql,封裝了一些常用的增刪改查方法。
  • 黑馬程式設計師:SpringBoot教程,SpringBoot高級之原理分析
    第一步:新建註解類新建ConditionOnClass註解類,增加@Conditional註解@Target({ElementType.TYPE, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME
  • 啥,聽說你用了springboot,但是開發的接口還在裸奔?
    id=5fe86eb74c636312f4b709551、應用場景簡介啥,聽說你用了springboot,但是開發的接口還在裸奔?快來試試這個PopularMVC吧,它也許是你想要找的神器!神器亮相springboot叫一鍵啟動,popularmvc為你的springboot項目插上翅膀,力求一鍵起飛!
  • 記mybatis應用在springboot中的一次踩坑記錄
    有次從網上找了個springboot+mybatis+redis的web應用框架。簡單了解了下項目架構,就匆匆上手,照葫蘆畫瓢的做了個簡單的CRUD。看到項目中源作者在UserMapper.xml文件中,沒有定義user類型直接可以在resultType和parameterType中只用。
  • SpringBoot+Mybatis動態切換數據源
    -- namespace:命名空間,用於隔離sql,還有一個很重要的作用,後面會講 --><mapper namespace="com.aesjourey.mybatisspringboot.dao.PersonMapper">    <select id="getPersonById" parameterType="String" resultType="com.aesjourey.mybatisspringboot.entity.Person
  • SpringBoot實現QQ郵箱註冊和登錄
    controller包是和前端對接的,mapper包中是接口,pojo是實體類,service層是邏輯代碼,vo包是前端發送數據暫時保存。 執行流程: 使用postman發送請求,controller中會接受,然後調用service中的邏輯代碼,service會調用的mapper中接口,mapper的對應的xml實現對資料庫的各種操作。