package com.gz.core.exception;

import com.gz.core.response.ResponseEnum;
import com.gz.core.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.stream.Collectors;

/**
 * 全局异常捕获
 *
 * @author LiuchangLan
 * @date 2020/6/27 22:19
 */
@Slf4j
@RestControllerAdvice
public class CustomExceptionEnumHandler {
    @ExceptionHandler(Exception.class)
    public ResponseResult exceptionHandler(Exception e) {
        // 控制台打印错误
        log.error(e.getMessage(), e);
        ResponseResult result = new ResponseResult();
        if (e instanceof BusinessException) {
            // 自定义错误处理
            BusinessException businessException = (BusinessException) e;
            result.setCode(businessException.getErrorCode());
            result.setMsg(businessException.getErrorMsg());
//        } else if (e instanceof NoHandlerFoundException) {
//            // 404
//            result.setCode(ResponseEnum.NOT_FOUND.getCode());
//            result.setMsg(ResponseEnum.NOT_FOUND.getMsg());
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            // 请求方式不对
            result.setCode(ResponseEnum.METHOD_ERROR.getCode());
            result.setMsg(ResponseEnum.METHOD_ERROR.getMsg());
        } else if (e instanceof ValidationException) {
            // 请求入参错误拦截
            result.setCode(400);
            String message = ((ConstraintViolationException) e).getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining());
            result.setMsg(message);
        } else if (e instanceof MethodArgumentNotValidException) {
            // 对象入参错误拦截
            result.setCode(400);
            String message = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
            result.setMsg(message);
        } else {
            // 其他错误
            result.setCode(500);
            result.setMsg(e.getMessage());
        }
        return result;
    }
}
