Spring boot 異常處理之最佳實踐

1. controller類內部異常處理器

@RestController
@RequestMapping("/exception")
public class ExceptionController
{
    @Autowired
    private UserService userService;

    @RequestMapping("/test1")
    public void exceptionHandler() throws Exception
    {
        userService.testUserServiceException();
    }

    @RequestMapping("/test2")
    public void exceptionHandler2() throws RuntimeException
    {
        throw new RuntimeException("test2");
    }

    @ExceptionHandler
    public void exceptionHandler(RuntimeException e)
    {
        System.out.println("In controller~");

        System.out.println(e.getMessage());
    }
}
在controller中加入被@ExceptionHandler修飾的方法即可(在該註解中指定該方法需要處理的那些異常類)
該異常處理方法只在當前的controller中起作用
如果同時定義了全局異常處理器,則不會走到全局異常處理方法

2. 全局異常處理器

2.1 定義異常枚舉類

public enum ExceptionEnum
{
    SUCCESS(0, "success"),
    ERROR(1, "myError"),
    UNKNOWN(-1, "unknown");

    private int code;
    private String msg;

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

    public int getCode()
    {
        return code;
    }

    public String getMsg()
    {
        return msg;
    }
}

2.2 自定義異常類

public class MyException extends RuntimeException
{
    public MyException(ExceptionEnum e)
    {
        super(e.getMsg());
    }
}
因爲某些業務需要進行業務回滾。但spring的事務只針對RuntimeException的進行回滾操作。所以需要回滾就要繼承RuntimeException。

2.3 定義 service 類

@Service
public class UserService
{
    public void testUserServiceException() throws Exception
    {
        throw new MyException(ExceptionEnum.ERROR);
    }
}

2.4 定義全局異常處理類

@RestControllerAdvice
public class MyExceptionHandler
{
    @ExceptionHandler(Exception.class)
    public String exceptionHandler(Exception e)
    {
        if(e instanceof MyException)
        {
            System.out.println("MyException~");
            System.out.println(e.getMessage());
            System.out.println("MyException~");
        }
        else
        {
            System.out.println("System Exception~");
            System.out.println(e.getMessage());
            System.out.println("System Exception~");
        }

        return e.getMessage();
    }
}

 

 

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