package com.fdkankan.web.controller;

import com.fdkankan.web.response.ResultData;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <p>
 * 404 500 401等错误返回转发接口，统一返回格式
 * </p>
 *
 * @author dengsixing
 * @since 2022/3/9
 **/
@Controller
public class CustomErrorController implements ErrorController {

    @RequestMapping("/error")
    @ResponseBody
    public ResultData handleError(HttpServletRequest request, HttpServletResponse response){

        //获取statusCode:401,404,500
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        String message = "";
        HttpStatus httpStatus = HttpStatus.valueOf(statusCode);
        switch (httpStatus){
            case INTERNAL_SERVER_ERROR :
                message = "服务器内部异常！";
                break;
            case NOT_FOUND:
                message = "接口不存在！";
                break;
            case FORBIDDEN:
                message = "禁止访问！";
                break;
        }
        return ResultData.error(statusCode, message);
    }


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