package com.crm.rely.backend.controller;

import com.crm.rely.backend.exception.DataNotFoundException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;

/**
 * 在路由为空404的时候进入当前控制器
 *
 * @author houn
 */
@Controller
public class NotFoundExceptionController implements ErrorController {

    @Value("${page.redirect.enable:false}")
    private boolean enable;

    @Value("${page.redirect.url:/error404.html}")
    private String url;

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

    /**
     * 抛出访问成功但页面不存在(not found)的信息
     *
     * @param httpServletResponse
     * @return
     * @throws Exception
     */
    @GetMapping(value = {"/error"})
    public Object error(HttpServletResponse httpServletResponse) throws Exception {
        httpServletResponse.setStatus(200);
        if (enable) {
            //todo 可以重定向到特定页面
            httpServletResponse.sendRedirect(url);
        } else {
            throw new DataNotFoundException("not found");
        }
        return null;
    }
}

