Skip to content

自定义系统异常

一.使用注解@ExceptionMapper(第一种方式)

新建异常处理类 继承 RuntimeException 在需要的异常类上面加入@ExceptionMapper

注解@ExceptionMapper
code错误码
msg错误信息
java
package com.chen.demo.exception;

import com.czh.tool.czh.tool.annotation.ExceptionMapper;

/**
 * @ClassNAME RatException
 * @Description TODO
 * @Author czh
 * @Date 2024/6/5 13:54
 * @Version 1.0
 */
@ExceptionMapper(code = 1002, msg = "有内鬼,终止交易")
public class RatException extends RuntimeException {

}

controller

java
    @GetMapping("test")
    public void test(){
       throw new RatException();
    }

image-20240605141509122

浏览器返回

image-20240605141530347

二.新建异常处理类 继承 CzhExceptionControllerAdvice (第二种方式)

java
package com.example.demo.controller;



import com.czh.tool.czh.tool.config.ValidatedExceptionConfig;
import com.czh.tool.czh.tool.exception.CzhExceptionControllerAdvice;
import com.czh.tool.czh.tool.response.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

/**
 * 异常处理类。
 * @author czh
 * @since 1.0
 */
//@Slf4j
@RestControllerAdvice()
public class ExceptionControllerAdvice extends CzhExceptionControllerAdvice {

    @Autowired
    private ValidatedExceptionConfig validatedExceptionConfig;

    /**
     * 参数非法(效验参数)异常 MethodArgumentNotValidException
     * @param e 参数异常类
     * @return 返回错误信息
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult handleValidException(MethodArgumentNotValidException e) {
//        log.error("数据效验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();

        Map<String,String> errMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            errMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return AjaxResult.error(100,"自定义校验异常")
                .put("data",errMap);
    }

    /**
     * 参数非法(效验参数)异常 ConstraintViolationException
     * @param e 参数异常类
     * @return 返回错误信息
     */
    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult handleValidException(ConstraintViolationException e) {
//        log.error("数据效验出现问题{},异常类型{}",e.getMessage(),e.getClass());
       e.getConstraintViolations();
        return AjaxResult.error(100,"自定义校验异常")
                .put("data",e.getMessage());
    }





}

image-20240522161633194

json

java
{
    "msg": "自定义校验异常",
    "code": 100,
    "data": {
        "id": "新增不能指定id"
    }
}

1.2自定义算数异常

java
package com.example.demo.controller;



import com.czh.tool.czh.tool.config.ValidatedExceptionConfig;
import com.czh.tool.czh.tool.exception.CzhExceptionControllerAdvice;
import com.czh.tool.czh.tool.response.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;

/**
 * 异常处理类。
 * @author czh
 * @since 1.0
 */
//@Slf4j
@RestControllerAdvice()
public class ExceptionControllerAdvice extends CzhExceptionControllerAdvice {

    @Autowired
    private ValidatedExceptionConfig validatedExceptionConfig;

    /**
     * 参数非法(效验参数)异常 MethodArgumentNotValidException
     * @param e 参数异常类
     * @return 返回错误信息
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult handleValidException(MethodArgumentNotValidException e) {
//        log.error("数据效验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();

        Map<String,String> errMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError) -> {
            errMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return AjaxResult.error(100,"自定义校验异常")
                .put("data",errMap);
    }


        /**
     * 参数非法(效验参数)异常 ConstraintViolationException
     * @param e 参数异常类
     * @return 返回错误信息
     */
    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult handleValidException(ConstraintViolationException e) {
//        log.error("数据效验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        e.getConstraintViolations();
        return AjaxResult.error(100,"自定义校验异常")
                .put("data",e.getMessage());
    }

    /**
     * (算数参数)异常 ArithmeticException
     * @param e 参数异常类
     * @return 返回错误信息
     */
    @ExceptionHandler({ArithmeticException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public AjaxResult handleArithmeticException(ArithmeticException e) {
//        log.error("数据效验出现问题{},异常类型{}",e.getMessage(),e.getClass());
        return AjaxResult.error(500,"除数不能为零")
                .put("data",e.getMessage());
    }





}

controller层

java
    /**
     * @return: void
     * @description:JSR303校验 新增接口
     * @author: czh
     * @date: 2024/1/8 15:57
     **/
    @PostMapping("/add")
    public void add(@RequestBody  @Validated({DiyGroup.class}) QueryVo queryVO) {
        int i=1/0;
    }

image-20240522162307845

Released 1.0.1