package com.spring.common.error;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class GlobalErrorController implements ErrorController {
    
    @ExceptionHandler(Throwable.class)
    @GetMapping("/error")
    public String handleError(HttpServletRequest request, Model model) {
        Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
        String errorMessage = String.valueOf(request.getAttribute(RequestDispatcher.ERROR_MESSAGE));
        String statusMsg = status.toString();
        HttpStatus httpStatus = HttpStatus.valueOf(Integer.valueOf(statusMsg));
        model.addAttribute("message", statusMsg + " " + httpStatus.getReasonPhrase());
        if (StringUtils.hasText(errorMessage)) model.addAttribute("errorMessage", errorMessage);
        return "pages/error/error";
    }

}
