SpringBoot进阶篇3:异常处理

在Springboot中处理异常分为全局异常和局部异常;一般解决方案如下:

局部异常处理: @Controller + @ExceptionHandler

全局异常处理: @ControllerAdvice + @ExceptionHandler

1、全局异常应用例子

1.1、定义异常枚举类

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

/**
 *异常枚举
 */
@Getter
@NoArgsConstructor
@AllArgsConstructor
public enum ExceptionEnum {
    PRICE_CANNOT_BE_NULL(400,"价格错误"),
    ;
    private int code;
    private String msg;
}

1.2、自定义异常结果VO类

import cn.jun.common.enums.ExceptionEnum;
import lombok.Data;
/**
 * 自定义异常结果vo类
 */
@Data
public class ExceptionResult {
    private int status;
    private String message;
    private Long timestamp;

    public ExceptionResult(ExceptionEnum em) {
        this.status=em.getCode();
        this.message=em.getMsg();
        this.timestamp=System.currentTimeMillis();
    }
}

1.3、自定义异常类

import cn.jun.common.enums.ExceptionEnum;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

/**
 * 自定义异常
 * @Description TODO
 * @Date 2018/11/911:17
 **/
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class LyException extends  RuntimeException {
    private ExceptionEnum exceptionEnum;
}

1.4、通用全局异常处理

import cn.jun.common.enums.ExceptionEnum;
import cn.jun.common.exception.LyException;
import cn.jun.common.vo.ExceptionResult;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;

/**
 * 通用异常处理
 * @Description TODO
 * @Date 2018/11/911:12
 **/
@ControllerAdvice
public class ExceptionHandler {
    public ResponseEntity handleExcepion(LyException e){
        ExceptionEnum em = e.getExceptionEnum();
        return ResponseEntity.status(em.getCode()).body(new ExceptionResult(e.getExceptionEnum()));
    }
}

 

你可能感兴趣的:(SpringBoot)