package com.esv.freight.file.common.handler;

import com.esv.freight.file.common.exception.EException;
import com.esv.freight.file.common.response.ECode;
import com.esv.freight.file.common.response.EResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

/**
 * @description:
 * @project: SpringCloudTemplate
 * @name: com.esv.springcloud.template.common.handler.RestExceptionHandler
 * @author: 黄朝斌
 * @email: huangchaobin@esvtek.com
 * @createTime: 2020/03/12 17:41
 * @version:1.0
 */
@Slf4j
@RestControllerAdvice
public class RestExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public EResponse defaultErrorHandler(HttpServletRequest req, Exception e) {
        EResponse r;
        if (e instanceof EException) {
            r = EResponse.error(((EException) e).getCode(), e.getMessage());
        } else if (e instanceof MethodArgumentNotValidException) {
            String message = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining("|"));
            r = EResponse.error(ECode.PARAM_ERROR.code(), ECode.PARAM_ERROR.message() + "[" + message + "]");
        } else if (e instanceof ConstraintViolationException) {
            String message = e.getMessage();
            if (message.contains(":")) {
                message = message.split(":")[1];
            }
            r = EResponse.error(ECode.PARAM_ERROR.code(), ECode.PARAM_ERROR.message() + "[" + message + "]");
        } else if (e instanceof MissingServletRequestParameterException || e instanceof HttpMessageNotReadableException) {
            r = EResponse.error(ECode.PARAM_ERROR.code(), ECode.PARAM_ERROR.message() + "[" + e.getMessage() + "]");
        } else {
            r = EResponse.error(ECode.SERVER_ERROR);
            log.error(e.getMessage(), e);
        }
        return r;
    }
}
