springboot2.2.6全局异常处理、统一返回值

1、返回值状态枚举

public enum Status {

    OK,

    ERROR;

}

2、定义返回值格式

import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * AjaxResult
 *
 * @desc: TODO 类的设计目的、功能及注意事项
 * @version:
 * @createTime: 2020/4/21 22:18
 * @author: 
 */
@Getter
@AllArgsConstructor(access= AccessLevel.PRIVATE)
public final class AjaxResult<T> {

    private Status status;

    private String msg;

    private T result;

    public static <T> AjaxResult<T> success(String msg, T result) {
        return new AjaxResult(Status.OK, msg, result);
    }

    public static <T> AjaxResult<T> success(T result) {
        return AjaxResult.success("操作成功", result);
    }

    public static <T> AjaxResult<T> success(String msg) {
        return AjaxResult.success(msg, (T)null);
    }

    public static AjaxResult success() {
        return AjaxResult.success("操作成功");
    }


    public static <T> AjaxResult<T> error(String msg, T result) {
        return new AjaxResult(Status.ERROR, msg, result);
    }

    public static <T> AjaxResult<T> error(T result) {
        return AjaxResult.error("操作失败", result);
    }

    public static <T> AjaxResult<T> error(String msg) {
        return AjaxResult.error(msg, (T)null);
    }

    public static AjaxResult error() {
        return AjaxResult.error("操作失败");
    }

}

3、自定义运行时异常

/**
 * BusinessException
 *
 * @desc: TODO 类的设计目的、功能及注意事项
 * @version:
 * @createTime: 2020/4/21 22:50
 * @author: 
 */
public class BusinessException extends RuntimeException {

    /** Constructs a new business exception with {@code null} as its
     * detail message.  The cause is not initialized, and may subsequently be
     * initialized by a call to {@link #initCause}.
     */
    public BusinessException() {
        super();
    }

    /** Constructs a new business exception with the specified detail message.
     * The cause is not initialized, and may subsequently be initialized by a
     * call to {@link #initCause}.
     *
     * @param   message   the detail message. The detail message is saved for
     *          later retrieval by the {@link #getMessage()} method.
     */
    public BusinessException(String message) {
        super(message);
    }

    /**
     * Constructs a new business exception with the specified detail message and
     * cause.  

Note that the detail message associated with * {@code cause} is not automatically incorporated in * this business exception's detail message. * * @param message the detail message (which is saved for later retrieval * by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public BusinessException(String message, Throwable cause) { super(message, cause); } /** Constructs a new business exception with the specified cause and a * detail message of (cause==null ? null : cause.toString()) * (which typically contains the class and detail message of * cause). This constructor is useful for business exceptions * that are little more than wrappers for other throwables. * * @param cause the cause (which is saved for later retrieval by the * {@link #getCause()} method). (A null value is * permitted, and indicates that the cause is nonexistent or * unknown.) * @since 1.4 */ public BusinessException(Throwable cause) { super(cause); } }

4、全局异常处理器

import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * GlobalExceptionHandler
 *
 * @desc: 全局异常处理器
 * @version:
 * @createTime: 2020/4/21 23:00
 * @author: 
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(BusinessException.class)
    public Object businessException(BusinessException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.error(e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public AjaxResult unKnowException(RuntimeException e) {
        log.error("运行时异常", e);
        return AjaxResult.error("运行时异常", e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public AjaxResult validatedBindException(BindException e) {
        log.error(e.getMessage(), e);
        return AjaxResult.error(
                e.getAllErrors().get(0).getDefaultMessage()
        );
    }

    @ExceptionHandler({ HttpRequestMethodNotSupportedException.class })
    public AjaxResult handleException(HttpRequestMethodNotSupportedException e) {
        log.error("不支持' " + e.getMethod() + "'请求", e);
        return AjaxResult.error("不支持' " + e.getMethod() + "'请求");
    }

 	@ExceptionHandler(MaxUploadSizeExceededException.class)
    public AjaxResult handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e){
        log.error("文件大小超出限制", e);
        return AjaxResult.error("文件大小超出限制", e.getMessage());
    }
   
    @ExceptionHandler(Exception.class)
    public AjaxResult handleException(Exception e) {
        log.error("服务器错误,请联系管理员", e);
        return AjaxResult.error("服务器错误,请联系管理员", e.getMessage());
    }

}

5、Controller层统一返回AjaxResult,方便前端处理

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