zhangfeng
2023-07-17 1e4e6a526682ddcd62378b1f2975e7d4b4b2de4f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.gk.hotwork.Domain.Exception.Handler;
 
import com.gk.hotwork.Domain.Exception.BusinessException;
import com.gk.hotwork.Domain.Exception.E;
import com.gk.hotwork.Domain.Utils.Msg;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
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;
 
@ControllerAdvice
public class CustomExceptionHandler {
 
    private Logger logger = LogManager.getLogger(CustomExceptionHandler.class);
    @ResponseBody
    @ExceptionHandler(value = BusinessException.class)
    public Msg errorHandler(BusinessException ex){
        logger.warn(ex);
        Msg msg = new Msg();
        msg.setCode("400");
        msg.setMessage(ex.getMessage());
        return msg;
    }
    /**
     * 处理入参异常
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Msg handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        logger.warn(e.getBindingResult().getFieldError().getDefaultMessage());
        return new Msg(E.DATA_PARAM_NULL.getCode(),e.getBindingResult().getFieldError().getDefaultMessage());
    }
}