package com.xhpc.evcs.http;

import com.xhpc.evcs.dto.CommonResponse;
import com.xhpc.evcs.encryption.EvcsConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
@Slf4j
public class GlobalExceptionController extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Throwable.class)
    public @ResponseBody
    CommonResponse handleAllException(Throwable e) {

        CommonResponse commonResponse = new CommonResponse();
        commonResponse.setRet(EvcsConst.RET_FAIL);
        commonResponse.setMsg(e.getMessage());
        e.printStackTrace();
        logger.error(e.getMessage());
        return commonResponse;
    }

    @Override
    protected ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException e,
                                                                          HttpHeaders headers, HttpStatus status,
                                                                          WebRequest request) {

        String name = e.getParameterName();
        logger.error(name + " parameter is missing");
        return super.handleMissingServletRequestParameter(e, headers, status, request);
    }

}
