SpringBoot的异常处理

本文介绍如何使用SpringBoot的@ControllerAdvice实现全局异常处理,通过自定义异常类和枚举类,对不同类型的异常进行统一捕获和响应。具体展示了如何在控制器中抛出自定义异常,并在通用异常处理类中进行捕获和处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot通过注解@ControllerAdive拦截所有由@Controller修饰的类。并根据异常类型进行响应的处理。

实例:

import com.leyou.common.enums.ExceptionEnum;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice    // 拦截所有由@Controller修饰的类,通用异常处理类
public class CommonExceptionHandler {

    @ExceptionHandler(LyException.class)  // 可以写多个,用于拦截不同的异常
    public ResponseEntity<String> handlerException(LyException e){
        ExceptionEnum em = e.getExceptionEnum();
        return ResponseEntity.status(em.getCode()).body(em.getMsg()); // 获取到异常时的消息,返回Rest风格的响应
    }
}

自定义异常:

import com.leyou.common.enums.ExceptionEnum;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;

@NoArgsConstructor
@AllArgsConstructor
@Getter
public class LyException extends RuntimeException {
    private ExceptionEnum exceptionEnum;
}

自定义枚举类:

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

@Getter
@AllArgsConstructor
@NoArgsConstructor
public enum ExceptionEnum {

    CATEGOTRY_NOT_FOND(404,"商品分类没查到")
    ;
    private int code;
    private String msg;
}

测试:

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptionEnum.LyException;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.pojo.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

@Service
public class CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    public List<Category> queryCategoryListByPid(Long pid) {
        Category category = new Category();
        category.setParentId(pid);
        List<Category> list = categoryMapper.select(category);
        if(CollectionUtils.isEmpty(list)){
            throw new LyException(ExceptionEnum.CATEGOTRY_NOT_FOND);
        }
        return null;
    }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值