1. 程式人生 > >Spring Cloud 全域性異常處理類

Spring Cloud 全域性異常處理類

這個是放在系統內部的 全域性異常處理類:

package com.hg.service.bussiness.system.execption;

import com.hg.core.code.BaseCode;
import com.hg.core.exception.BaseException;
import com.hg.core.exception.ErrorInfo;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(value = BaseException.class)
@ResponseBody
public ErrorInfo<Object> baseErrorHandler(BaseException e) throws Exception {
    ErrorInfo<Object> r = new ErrorInfo<>();
    r.setMessage(e.getMessage());
    r.setCode(e.getCode());
    return r;
}

@ExceptionHandler(value = Exception.class)
@ResponseBody
public ErrorInfo<Object> exceptionErrorHandler(Exception e) throws Exception {
    ErrorInfo<Object> r = new ErrorInfo<>();
    r.setMessage(BaseCode.FAIL.getMessage());
    r.setCode(BaseCode.FAIL.getCode());
    return r;
}

}

@ControllerAdvice 這個註解會掃所有的controller包

第一個方法是自定義異常

第二個方法的未知異常的獲取

controller 的異常就可以直接丟擲了 或者 寫在 catch 都可以了

下面貼個簡單的例子 :

package com.hg.service.bussiness.controller;

import com.hg.group.service.api.bussiness.BussinessApi;
import org.springframework.mail.MailParseException;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hg.core.exception.BaseException;

import java.util.Map;

@RestController
@RequestMapping(“/bussiness”)
public class BussinessController {

@RequestMapping(value = "/test" , produces = {"application/json;charset=UTF-8"})
public String testFail() {
    try {
        Map map = null;
        map.get("qq");
        return "aaa";
    } catch (Exception e) {
        throw new BaseException("測試異常");
    }
}

@RequestMapping("/testa")
public String testSuccess() {
    throw new NullPointerException("測試異常");
}

}
補充一點 @RequestMapping(value = “/test” , produces = {“application/json;charset=UTF-8”})
這個加粗的 是讓返回的 xml 轉json