springboot 기본 예외 처리

SpringBoot은 기본적으로 사용자 정의 이상 처리 시스템이 있습니다. SpringBoot 프로젝트를 할 때 실행 중 이상이 발생하면 springBoot은 이상을 처리하고 다음과 같은 이상 정보를 되돌려줍니다.
{
    "timestamp": 1517294278132,
    "status": 500,
    "error": "Internal Server Error",
    "exception": "com.lgy.common.exception.BusinessException",
    "message": "[001] uncheck  !",
    "path": "/validateExceptionTest"
}
그 원인을 추궁하여 SpirngBoot에 이상 정보가 발견되면/error에 기본적으로 접근합니다. springBoot에는 BasicErrorController 종류가 있어 이상 정보를 처리합니다.
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package org.springframework.boot.autoconfigure.web;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.boot.autoconfigure.web.ErrorProperties.IncludeStacktrace;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class BasicErrorController extends AbstractErrorController {
    private final ErrorProperties errorProperties;

    public BasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties) {
        this(errorAttributes, errorProperties, Collections.emptyList());
    }

    public BasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List errorViewResolvers) {
        super(errorAttributes, errorViewResolvers);
        Assert.notNull(errorProperties, "ErrorProperties must not be null");
        this.errorProperties = errorProperties;
    }

    public String getErrorPath() {
        return this.errorProperties.getPath();
    }

    @RequestMapping(
        produces = {"text/html"}
    )
    public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
        HttpStatus status = this.getStatus(request);
        Map model = Collections.unmodifiableMap(this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.TEXT_HTML)));
        response.setStatus(status.value());
        ModelAndView modelAndView = this.resolveErrorView(request, response, status, model);
        return modelAndView == null?new ModelAndView("error", model):modelAndView;
    }

    @RequestMapping
    @ResponseBody
    public ResponseEntity> error(HttpServletRequest request) {
        Map body = this.getErrorAttributes(request, this.isIncludeStackTrace(request, MediaType.ALL));
        HttpStatus status = this.getStatus(request);
        return new ResponseEntity(body, status);
    }

    protected boolean isIncludeStackTrace(HttpServletRequest request, MediaType produces) {
        IncludeStacktrace include = this.getErrorProperties().getIncludeStacktrace();
        return include == IncludeStacktrace.ALWAYS?true:(include == IncludeStacktrace.ON_TRACE_PARAM?this.getTraceParameter(request):false);
    }

    protected ErrorProperties getErrorProperties() {
        return this.errorProperties;
    }
}

SpringBoot의 기본 비정상 처리 방식을 대체하려면 ErrorController를 상속합니다.
package com.lgy.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.BasicErrorController;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by fengch on 2018/1/30.
 */
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class FundaErrorController  implements ErrorController {
    private static final String PATH = "/error";

    @Autowired
    private ErrorAttributes errorAttributes;

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


    @RequestMapping
    @ResponseBody
    public JSONObject doHandleError(HttpServletRequest request) {
        RequestAttributes requestAttributes = new ServletRequestAttributes(request);
        Map errorAttributesData = errorAttributes.getErrorAttributes(requestAttributes,true);
        Integer status=(Integer)errorAttributesData.get("status");  // 
        String path=(String)errorAttributesData.get("path");        // 
        String messageFound=(String)errorAttributesData.get("message");   // 

        JSONObject reData = new JSONObject();
        reData.put("status_", status);
        reData.put("path_", path);
        reData.put("message", messageFound);
        return reData;
    }
}

다음으로 액세스하여 사용자 지정 처리된 예외 정보입니다.
{
    "message": "[001] uncheck  !",
    "path_": "/validateExceptionTest",
    "status_": 500
}

좋은 웹페이지 즐겨찾기