package cn.wise.sc.energy.power.plant.business.config;

import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import org.springframework.boot.autoconfigure.web.servlet.error.AbstractErrorController;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
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.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
@RestController
public class GlobalDefaultExceptionHandler extends AbstractErrorController {

    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public BaseResponse defaultErrorHandler(HttpServletResponse response, RuntimeException e) {
        return BaseResponse.errorMsg(e.getMessage());
    }

    public GlobalDefaultExceptionHandler(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }


    private static final String ERROR_PATH = "/error";
    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }

    private Throwable getError(WebRequest webRequest) {
        return (Throwable) this.getAttribute(webRequest, "javax.servlet.error.exception");
    }

    private Object getAttribute(RequestAttributes requestAttributes, String name) {
        return requestAttributes.getAttribute(name, 0);
    }
}