web項目全局異常處理方案

一. 使用@ControllerAdvice+@ExceptionHandler註解

目的:在控制層不需要再寫如下的代碼了

try{
	// 業務邏輯
} catch(BusinessException b) {
	// 日誌打印
	// 業務異常處理
} catch(Exception e) {
	// 日誌打印
	// 非業務異常處理
}
  1. 構建一個springboot項目(引入依賴spring-boot-starter-web)
    啓動類如下:
package com.bigzone.springbootdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.scheduling.annotation.EnableScheduling;

// 暫不使用數據庫, 所以取消數據源自動配置, 不然會報錯
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class SpringbootDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootDemoApplication.class, args);
    }
}
  1. 編寫統一返回值類型JsonResult, 適用restful風格
package com.bigzone.springbootdemo.common;

import java.io.Serializable;

/**
 * @author wangxq
 * @date 2019/10/9
 * 統一返回格式類
 */
public class JsonResult implements Serializable {
    private static final long serialVersionUID = -4917497061692852616L;

    private static final int SUCCESS_CODE = 0;
    private static final int ERROR_CODE = 1;
    private static final String SUCCESS_MSG = "成功";

    private Integer code;
    private String msg;
    private Object data;

    public JsonResult() {
    }

    public JsonResult(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public JsonResult(Integer code, String msg, Object data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public static JsonResult success(Object data){
        return new JsonResult(SUCCESS_CODE, SUCCESS_MSG, data);
    }

    public static JsonResult failure(String msg) {
        return new JsonResult(ERROR_CODE, msg);
    }
}

  1. 編寫自定義異常類
package com.bigzone.springbootdemo.exception;

/**
 * @author wangxq
 * @date 2019/10/10
 * 自定義業務異常類
 */
public class BusinessException extends RuntimeException {
    public BusinessException() {
    }

    public BusinessException(String message) {
        super(message);
    }
}
  1. 編寫全局異常處理類(@RestControllerAdvice = @ControllerAdvice + @ResponseBody + …)
package com.bigzone.springbootdemo.exception;

import com.bigzone.springbootdemo.common.JsonResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author wangxq
 * @date 2019/10/10
 * 全局異常處理類
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public JsonResult businessExceptionHandler(BusinessException b) {
        System.out.println(b.getMessage());
        return JsonResult.failure(b.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public JsonResult exceptionHandler(Exception e) {
        e.printStackTrace();
        return JsonResult.failure("請求失敗!");
    }

}
  1. 編寫控制層
package com.bigzone.springbootdemo.controller;

import com.bigzone.springbootdemo.common.JsonResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author wangxq
 * @date 2019/10/9
 */
@RestController
@RequestMapping("/test/")
public class TestResultController {

    @GetMapping("getData1")
    public JsonResult getData1() {
        int a = 10/0;
        return JsonResult.success("success");
    }

	@GetMapping("getData2")
    public JsonResult getData2() {
        if (true) {
            throw new BusinessException("業務異常...");
        }
        return JsonResult.success("success");
    }

}
  1. 測試結果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章