springboot项目中的异常处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Cainiao111112/article/details/82883297

1.首先自定义异常类继承RuntimeException类,以NotFoundException为例:

使用MessageFormat.format()方法做信息和可变参的处理。

public class NotFoundException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    public NotFoundException(String msg, Object... obj) {
        super(MessageFormat.format(msg, obj));
    }
}

2.定义全局异常处理类,将自定义的异常注册到其中。

@RestControllerAdvice
@Component
public class GlobalDefaultExceptionHandler {

    /**
     * 404异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(NotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ErrorMsg notFoundException(NotFoundException e) {
        return new ErrorMsg(404, e.getMessage());
    }

    /**
     * 409异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(ExistedException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    public ErrorMsg existedException(ExistedException e) {
        return new ErrorMsg(409, e.getMessage());
    }

    /**
     * 403
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(UnAuthenticationException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public ErrorMsg unAuthenticationException(UnAuthenticationException e) {
        return new ErrorMsg(403, e.getMessage());
    }

    /**
     * 400 json格式异常
     * 
     * @param e
     * @return
     */
    @ExceptionHandler(JsonSchemaException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ErrorMsg jsonSchemaException(JsonSchemaException e) {
        return new ErrorMsg(400, e.getMessage());
    }

}

3.接下来只要在需要抛出异常的位置,抛出自定义异常即可。

猜你喜欢

转载自blog.csdn.net/Cainiao111112/article/details/82883297