All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.hothub.module.common.exception.AppErrorController Maven / Gradle / Ivy

The newest version!
package org.hothub.module.common.exception;

import org.hothub.module.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;


@Controller
public class AppErrorController implements ErrorController {

    private final static String ERROR_PATH = "error";

    @Value(value = "${properties.error.view-path:error}")
    private String ERROR_VIEW_PATH;

    @Value(value = "${properties.error.page-type:html}")
    private String ERROR_PAGE_TYPE;


    @Override
    public String getErrorPath() {
        return ERROR_PATH;
    }



    /**
     * 重写error方法,禁止Whitelabel Error Page页,返回统一JSON
     *
     * @param request servletRequest
     * @return ModelAndView
     * @throws NoHandlerFoundException 404
     */
    @ResponseBody
    @RequestMapping(value = ERROR_PATH)
    public ModelAndView error(HttpServletRequest request) throws NoHandlerFoundException {
        String pageType = StringUtils.isEmpty(ERROR_PAGE_TYPE) ? "" : ERROR_PAGE_TYPE.toLowerCase();

        ModelAndView modelAndView = new ModelAndView();

        if (pageType.equals("json")) {
            throw new NoHandlerFoundException("GET", request.getRequestURI(), null);
        } else {
            modelAndView.setViewName(ERROR_VIEW_PATH);
        }

        return modelAndView;
    }



}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy