Springboot 的錯誤處理功能的實現

1、頁面的形式返回html

   直接在resources的目錄下建立public/error的路徑,而後建立5xx.html或者4xx.html文件,若是出錯就會自動跳轉的相應的頁面。前端

2、cotroller的形式返回錯誤的處理java

    1.自定義錯誤處理類web

    

package com.kiyozawa.manager.error;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletRequestAttributes;

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

/**
 * 自定義錯誤處理
 */
public class MyErrorController extends BasicErrorController {

    public MyErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
    }

//        {
//            "timestamp": "2019-03-02 13:19:46.066",
//               x "status": 500,
//                x"error": "Internal Server Error",
//               x "exception": "java.lang.IllegalArgumentException",
//                "message": "編號不可爲空",
//               x "path": "/manager/products"
//        }


    @Override
    protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) {
        Map<String, Object> attrs = super.getErrorAttributes(request, includeStackTrace);
       //去除返回值中沒必要要的信息
        attrs.remove("timestamp");
        attrs.remove("status");
        attrs.remove("error");
        attrs.remove("exception");
        attrs.remove("path");
        //經過信息獲取errorCode的值,最終獲取errorEnum類的信息
        String errorCode = (String) attrs.get("message");
        ErrorEnum errorEnum = ErrorEnum.getByCode(errorCode);
        //ErrorEnum類的信息存入attrs中返回給前端
        attrs.put("message",errorEnum.getMessage());
        attrs.put("code",errorEnum.getCode());
        attrs.put("canRetry",errorEnum.isCanRetry());
        return attrs;
    }
}

把錯誤處理類自動配置到Springboot中spring

package com.kiyozawa.manager.error;

import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.boot.autoconfigure.web.ErrorViewResolver;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
public class ErrorConfiguration {
    @Bean
    public MyErrorController basicErrorController(ErrorAttributes errorAttributes, ServerProperties serverProperties,
                                                  ObjectProvider<List<ErrorViewResolver>> errorViewResolversProvider) {
        return new MyErrorController(errorAttributes, serverProperties.getError(),
                errorViewResolversProvider.getIfAvailable());
    }
}

自定義錯誤類型ide

package com.kiyozawa.manager.error;

public enum ErrorEnum {
    ID_NoT_NULL("F001","編碼不爲空",false),
    UNKOWN("000","位置異常",false);
    private String code;
    private String message;
    private boolean canRetry;
    ErrorEnum(String code,String message,boolean canRetry){
        this.code=code;
        this.message=message;
        this.canRetry=canRetry;
    }
    public static ErrorEnum getByCode(String code){
        for (ErrorEnum errorEnum:ErrorEnum.values()){
            if(errorEnum.code.equals(code)){
                return errorEnum;
            }
        }
        return UNKOWN;

    }

    public String getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }

    public boolean isCanRetry() {
        return canRetry;
    }
}

另外的一種方式見下:this

package com.kiyozawa.manager.error;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 統一錯誤處理
 */
//路徑爲controller類的路徑
@ControllerAdvice(basePackages = {"com.kiyozawa.manager.controller"}) public class ErrorControllerAdvice { @ExceptionHandler(Exception.class) @ResponseBody public ResponseEntity handleException(Exception e){ Map<String, Object> attrs = new HashMap(); String errorCode = e.getMessage(); ErrorEnum errorEnum = ErrorEnum.getByCode(errorCode); attrs.put("message",errorEnum.getMessage()); attrs.put("code",errorEnum.getCode()); attrs.put("canRetry",errorEnum.isCanRetry()); attrs.put("type","advice"); // Assert.isNull(attrs,"advice"); return new ResponseEntity(attrs, HttpStatus.INTERNAL_SERVER_ERROR); } }
相關文章
相關標籤/搜索