package com.casic.missiles.handler;
import com.casic.missiles.dto.ReturnUtil;
import com.casic.missiles.enums.BusinessExceptionEnum;
import com.casic.missiles.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* @Description: 全局异常处理
* @Author: wangpeng
* @Date: 2022/11/24 8:50
*/
@Slf4j
@Order(1)
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 业务异常捕获处理
*/
@ResponseBody
@ExceptionHandler({BusinessException.class})
public Object handleError(BusinessException exception) {
return ReturnUtil.failed(exception.getCode(), exception.getMessage());
}
/**
* 编号重复异常捕获处理
*/
@ResponseBody
@ExceptionHandler({DuplicateKeyException.class})
public Object handleDuplicateKeyException() {
return ReturnUtil.failed(BusinessExceptionEnum.DUPLICATE_NUMBER.getCode(), BusinessExceptionEnum.DUPLICATE_NUMBER.getMessage());
}
/**
* 参数校验失败异常
*/
@ResponseBody
@ExceptionHandler({MethodArgumentNotValidException.class})
public Object handleMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
return ReturnUtil.failed(BusinessExceptionEnum.PARAM_INVALID.getCode(), exception.getFieldError().getDefaultMessage());
}
}