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 baseErrorHandler(BaseException e) throws Exception {
    ErrorInfo r = new ErrorInfo<>();
    r.setMessage(e.getMessage());
    r.setCode(e.getCode());
    return r;
}

@ExceptionHandler(value = Exception.class)
@ResponseBody
public ErrorInfo exceptionErrorHandler(Exception e) throws Exception {
    ErrorInfo 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

你可能感兴趣的:(Spring,Cloud)