package cn.com.capcloud.core.system.exception;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.WebRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author LiaoJiaHui
 * @Create 2024/11/16 20:39
 */
@RestController
public class CustomErrorController implements ErrorController {

    private final ErrorAttributes errorAttributes;

    @Autowired
    public CustomErrorController(ErrorAttributes errorAttributes) {
        this.errorAttributes = errorAttributes;
    }

    @RequestMapping("/error")
    public Map<String, Object> handleError(WebRequest webRequest, ErrorAttributeOptions options) {
        // 获取错误的详细信息
        Map<String, Object> errorDetails = errorAttributes.getErrorAttributes(webRequest, options);

        // 获取错误信息
        String errorMessage = (String) errorDetails.get("message");
        Integer statusCode = (Integer) errorDetails.get("status");

        Map<String, Object> response = new HashMap<>();
        response.put("status", statusCode);
        response.put("message", errorMessage);
        return response;
    }

}
