package com.weather.common.exception;

import com.weather.vo.ApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author : fengyuhao
 * @desc : 自定义404错误处理：主要是解决未被全局异常处理的错误
 * 如果设置资源映射文件不存在：spring.resources.add-mappings 会导致swagger druid等web页面不能访问
 * @update : 修改说明
 * @date : 2020/3/1-00:12
 */
@Slf4j
@RestController
public class NotFoundException implements ErrorController {

    @Override
    public String getErrorPath() {
        return "/error";
    }

    @RequestMapping(value = {"/error"})
    @ResponseBody
    public ApiResult error(HttpServletRequest request, HttpServletResponse response) {
        log.error("请求地址-参数等客户端错误:response error,url:{}", request.getRequestURI());
        log.error("请求地址-参数等客户端错误:response error,httpCode:{}",response.getStatus());

        // 错误处理逻辑
        int status = response.getStatus();
        if (status == 404) {
            return ApiResult.error("访问地址不存在");
        } else if (status == 500) {
            return ApiResult.error("服务器运行异常");
        } else if (status >= 100 && status < 200) {
            return ApiResult.error("未知错误1xx");
        } else if (status >= 300 && status < 400) {
            return ApiResult.error("未知错误3xx");
        } else if (status >= 400 && status < 500) {
            return ApiResult.error("未知错误4xx");
        } else {
            return ApiResult.error("服务器运行异常");
        }
    }

}
