Spring通用异常处理

异常处理
在这里插入图片描述

1)引入springmvc依赖包

<!--引入异常处理-->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
</dependency>

2)创建异常信息枚举

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

@Getter
@AllArgsConstructor
@NoArgsConstructor
public enum ExceptionEnum {

    PARENT_ID_CANNOT_BE_NULL(400,"分类父ID不能为空!")
    ;

    private int code;
    private String msg;
}

2)创建异常结果

import cn.wangkf.common.enums.ExceptionEnum;
import lombok.Data;

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

3)编写自定义异常类

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

@NoArgsConstructor
@AllArgsConstructor
@Getter
public class LgException extends RuntimeException {

    private ExceptionEnum exceptionEnum;
}

4)编写全局异常处理类

import cn.wangkf.common.enums.ExceptionEnum;
import cn.wangkf.common.exception.LgException;
import cn.wangkf.common.vo.ExceptionResult;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class CommonExceptionHandler {
    /*@ExceptionHandler(RuntimeException.class)
    public ResponseEntity<String> handleException(RuntimeException e){
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
    }*/
    @ExceptionHandler(LgException.class)
    public ResponseEntity<String> handleException(LgException e){
        ExceptionEnum em  = e.getExceptionEnum();
        return ResponseEntity.status(em.getCode()).body(em.getMsg());
    }
}

5)异常抛出测试

/**
 * 保存
 * @return
 * 异常处理demo
 *
 */
@PostMapping
public ResponseEntity<Category> saveCategory(Category category){
    if (category.getParentId() == null){
        //throw new RuntimeException("分类父ID不能为空!");
        throw new LgException(ExceptionEnum.PARENT_ID_CANNOT_BE_NULL);
    }
    category = categoryService.saveCategoryDemo(category);
    return ResponseEntity.status(HttpStatus.CREATED).body(category);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值