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;
}
}