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();
    }
}

 

 

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