package com.qiaoba.common.web.advice;


import com.qiaoba.common.base.exception.ServiceException;
import com.qiaoba.common.base.result.AjaxResult;
import org.springframework.validation.BindException;
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;

import javax.validation.ConstraintViolationException;
import java.util.Objects;

/**
 * 全局异常处理
 *
 * @author ailanyin
 * @version 1.0
 * @since 2021/10/15 0015 下午 16:43
 */
@ControllerAdvice
public class ExceptionAdvice {

    /**
     * 非自定义异常
     *
     * @param e Exception
     * @return AjaxResult
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public AjaxResult error(Exception e) {
        e.printStackTrace();
        return AjaxResult.error(e.getMessage());
    }

    /**
     * 自定义异常, 控制台不打印
     *
     * @param e ServiceException
     * @return AjaxResult
     */
    @ExceptionHandler(ServiceException.class)
    @ResponseBody
    public AjaxResult handlerServiceException(ServiceException e) {
        return Objects.isNull(e.getErrorCode()) ? AjaxResult.error(e.getMessage()) : AjaxResult.error(e.getErrorCode(), e.getMessage());
    }

    /**
     * 参数校验
     *
     * @param e MethodArgumentNotValidException
     * @return AjaxResult
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public AjaxResult handlerValidException(MethodArgumentNotValidException e) {
        return AjaxResult.error(Objects.isNull(e.getBindingResult().getFieldError()) ? e.getMessage() : e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 参数校验
     *
     * @param e BindException
     * @return AjaxResult
     */
    @ExceptionHandler({BindException.class})
    @ResponseBody
    public AjaxResult handlerValidException(BindException e) {
        return AjaxResult.error(Objects.isNull(e.getBindingResult().getFieldError()) ? e.getMessage() : e.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 参数校验
     *
     * @param e ConstraintViolationException
     * @return AjaxResult
     */
    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseBody
    public AjaxResult handlerValidException(ConstraintViolationException e) {
        return AjaxResult.error(e.getMessage());
    }

}
