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

com.nxyfan.framework.common.exception.CommonErrorViewHandler Maven / Gradle / Ivy

package com.nxyfan.framework.common.exception;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.Map;

/**
 * 全局异常页面处理器,覆盖默认的Whitelabel Error Page
 *
 * @author amour
 * @date 2022/2/11 15:41
 **/
@RestController
public class CommonErrorViewHandler extends BasicErrorController {

    public CommonErrorViewHandler(ServerProperties serverProperties) {
        super(new CommonErrorAttributesHandler(), serverProperties.getError());
    }

    /**
     * 覆盖默认的Json响应
     *
     * @author amour
     * @date 2022/2/11 15:47
     **/
    @Override
    public ResponseEntity> error(HttpServletRequest request) {
        Map defaultErrorAttributes = super.getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        Integer code = Convert.toInt(defaultErrorAttributes.get("rspCode"));
        return new ResponseEntity<>(defaultErrorAttributes, HttpStatus.valueOf(ObjectUtil.isNotEmpty(code)?code:500));
    }

    /**
     * 覆盖默认的错误页面,响应JSON
     *
     * @author amour
     * @date 2022/2/12 21:55
     */
    @Override
    @RequestMapping(produces = {"text/html"})
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = this.getStatus(request);
        Map model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.getErrorAttributeOptions(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());
        ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
        request.setAttribute("model", model);
        return modelAndView != null ? modelAndView : new ModelAndView("errorView", model);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy