最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot初始教程之統(tǒng)一異常處理詳解

 更新時(shí)間:2017年04月06日 16:48:23   作者:尊少  
本篇文章主要介紹了SpringBoot初始教程之統(tǒng)一異常處理詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

1.介紹

在日常開發(fā)中發(fā)生了異常,往往是需要通過一個(gè)統(tǒng)一的異常處理處理所有異常,來保證客戶端能夠收到友好的提示。SpringBoot在頁面發(fā)生異常的時(shí)候會自動把請求轉(zhuǎn)到/error,SpringBoot內(nèi)置了一個(gè)BasicErrorController對異常進(jìn)行統(tǒng)一的處理,當(dāng)然也可以自定義這個(gè)路徑

application.yaml

server:
 port: 8080
 error:
 path: /custom/error

BasicErrorController提供兩種返回錯(cuò)誤一種是頁面返回、當(dāng)你是頁面請求的時(shí)候就會返回頁面,另外一種是json請求的時(shí)候就會返回json錯(cuò)誤

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

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

分別會有如下兩種返回

{
 "timestamp": 1478571808052,
 "status": 404,
 "error": "Not Found",
 "message": "No message available",
 "path": "/rpc"
}

2.通用Exception處理

通過使用@ControllerAdvice來進(jìn)行統(tǒng)一異常處理,@ExceptionHandler(value = Exception.class)來指定捕獲的異常

下面針對兩種異常進(jìn)行了特殊處理分別返回頁面和json數(shù)據(jù),使用這種方式有個(gè)局限,無法根據(jù)不同的頭部返回不同的數(shù)據(jù)格式,而且無法針對404、403等多種狀態(tài)進(jìn)行處理

 @ControllerAdvice
 public class GlobalExceptionHandler {
  public static final String DEFAULT_ERROR_VIEW = "error";
  @ExceptionHandler(value = CustomException.class)
  @ResponseBody
  public ResponseEntity defaultErrorHandler(HttpServletRequest req, CustomException e) throws Exception {
   return ResponseEntity.ok("ok");
  }
  @ExceptionHandler(value = Exception.class)
  public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception {
   ModelAndView mav = new ModelAndView();
   mav.addObject("exception", e);
   mav.addObject("url", req.getRequestURL());
   mav.setViewName(DEFAULT_ERROR_VIEW);
   return mav;
  }
 }

3.自定義BasicErrorController 錯(cuò)誤處理

在初始介紹哪里提到了BasicErrorController,這個(gè)是SpringBoot的默認(rèn)錯(cuò)誤處理,也是一種全局處理方式。咱們可以模仿這種處理方式自定義自己的全局錯(cuò)誤處理

下面定義了一個(gè)自己的BasicErrorController,可以根據(jù)自己的需求自定義errorHtml()和error()的返回值。

 @Controller
 @RequestMapping("${server.error.path:${error.path:/error}}")
 public class BasicErrorController extends AbstractErrorController {
  private final ErrorProperties errorProperties;
  private static final Logger LOGGER = LoggerFactory.getLogger(BasicErrorController.class);
  @Autowired
  private ApplicationContext applicationContext;

  /**
   * Create a new {@link org.springframework.boot.autoconfigure.web.BasicErrorController} instance.
   *
   * @param errorAttributes the error attributes
   * @param errorProperties configuration properties
   */
  public BasicErrorController(ErrorAttributes errorAttributes,
         ErrorProperties errorProperties) {
   this(errorAttributes, errorProperties,
     Collections.<ErrorViewResolver>emptyList());
  }

  /**
   * Create a new {@link org.springframework.boot.autoconfigure.web.BasicErrorController} instance.
   *
   * @param errorAttributes the error attributes
   * @param errorProperties configuration properties
   * @param errorViewResolvers error view resolvers
   */
  public BasicErrorController(ErrorAttributes errorAttributes,
         ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
   super(errorAttributes, errorViewResolvers);
   Assert.notNull(errorProperties, "ErrorProperties must not be null");
   this.errorProperties = errorProperties;
  }

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

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



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

  /**
   * Determine if the stacktrace attribute should be included.
   *
   * @param request the source request
   * @param produces the media type produced (or {@code MediaType.ALL})
   * @return if the stacktrace attribute should be included
   */
  protected boolean isIncludeStackTrace(HttpServletRequest request,
            MediaType produces) {
   ErrorProperties.IncludeStacktrace include = getErrorProperties().getIncludeStacktrace();
   if (include == ErrorProperties.IncludeStacktrace.ALWAYS) {
    return true;
   }
   if (include == ErrorProperties.IncludeStacktrace.ON_TRACE_PARAM) {
    return getTraceParameter(request);
   }
   return false;
  }

  /**
   * Provide access to the error properties.
   *
   * @return the error properties
   */
  protected ErrorProperties getErrorProperties() {
   return this.errorProperties;
  }
 }

SpringBoot提供了一種特殊的Bean定義方式,可以讓我們?nèi)菀椎母采w已經(jīng)定義好的Controller,原生的BasicErrorController是定義在ErrorMvcAutoConfiguration中的

具體代碼如下:

 @Bean
 @ConditionalOnMissingBean(value = ErrorController.class, search = SearchStrategy.CURRENT)
 public BasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
  return new BasicErrorController(errorAttributes, this.serverProperties.getError(),
    this.errorViewResolvers);
 }

可以看到這個(gè)注解@ConditionalOnMissingBean 意思就是定義這個(gè)bean 當(dāng) ErrorController.class 這個(gè)沒有定義的時(shí)候, 意思就是說只要我們在代碼里面定義了自己的ErrorController.class時(shí),這段代碼就不生效了,具體自定義如下:

 @Configuration
 @ConditionalOnWebApplication
 @ConditionalOnClass({Servlet.class, DispatcherServlet.class})
 @AutoConfigureBefore(WebMvcAutoConfiguration.class)
 @EnableConfigurationProperties(ResourceProperties.class)
 public class ConfigSpringboot {
  @Autowired(required = false)
  private List<ErrorViewResolver> errorViewResolvers;
  private final ServerProperties serverProperties;

  public ConfigSpringboot(
    ServerProperties serverProperties) {
   this.serverProperties = serverProperties;
  }

  @Bean
  public MyBasicErrorController basicErrorController(ErrorAttributes errorAttributes) {
   return new MyBasicErrorController(errorAttributes, this.serverProperties.getError(),
     this.errorViewResolvers);
  }
 }

在使用的時(shí)候需要注意MyBasicErrorController不能被自定義掃描Controller掃描到,否則無法啟動。

3.總結(jié)

一般來說自定義BasicErrorController這種方式比較實(shí)用,因?yàn)榭梢酝ㄟ^不同的頭部返回不同的數(shù)據(jù)格式,在配置上稍微復(fù)雜一些,但是從實(shí)用的角度來說比較方便而且可以定義通用組件

本文代碼:SpringBoot-Learn_jb51.rar

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • mybatis如何根據(jù)表逆向自動化生成代碼實(shí)例

    mybatis如何根據(jù)表逆向自動化生成代碼實(shí)例

    逆向工程是一個(gè)專門為 MyBatis 框架使用者設(shè)計(jì)的代碼生成器,可以根據(jù)數(shù)據(jù)庫中的表字段名,自動生成 POJO 類,mapper 接口與 SQL 映射文件,這篇文章主要給大家介紹了關(guān)于mybatis如何根據(jù)表逆向自動化生成代碼的相關(guān)資料,需要的朋友可以參考下
    2021-08-08
  • Scala遞歸函數(shù)調(diào)用自身

    Scala遞歸函數(shù)調(diào)用自身

    這篇文章主要介紹了Scala遞歸函數(shù),Scala遞歸函數(shù)是一種函數(shù)可以調(diào)用自身的函數(shù),直到滿足某個(gè)特定的條件為止。在函數(shù)式編程的語言中,遞歸函數(shù)起著重要的作用,因?yàn)樗梢杂脕肀硎狙h(huán)或迭代的邏輯
    2023-04-04
  • springboot自動配置原理解析

    springboot自動配置原理解析

    這篇文章主要介紹了springboot自動配置原理解析,幫助大家更好的理解和學(xué)習(xí)使用springboot,感興趣的朋友可以了解下
    2021-04-04
  • java 中newInstance()方法和new關(guān)鍵字的區(qū)別

    java 中newInstance()方法和new關(guān)鍵字的區(qū)別

    這篇文章主要介紹了java 中newInstance()方法和new關(guān)鍵字的區(qū)別的相關(guān)資料,希望通過本文大家能掌握他們之家的區(qū)別與用法,需要的朋友可以參考下
    2017-09-09
  • 解決spring boot網(wǎng)關(guān)gateway導(dǎo)致的坑,無法下載文件問題

    解決spring boot網(wǎng)關(guān)gateway導(dǎo)致的坑,無法下載文件問題

    這篇文章主要介紹了解決spring boot網(wǎng)關(guān)gateway導(dǎo)致的坑,無法下載文件的問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Mybatis日志參數(shù)快速替換占位符工具的詳細(xì)步驟

    Mybatis日志參數(shù)快速替換占位符工具的詳細(xì)步驟

    這篇文章主要介紹了Mybatis日志參數(shù)快速替換占位符工具的詳細(xì)步驟,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-08-08
  • 跳表的由來及Java實(shí)現(xiàn)詳解

    跳表的由來及Java實(shí)現(xiàn)詳解

    跳表(Skip List)是一種基于鏈表的數(shù)據(jù)結(jié)構(gòu),它可以支持快速的查找、插入、刪除操作,本文主要來和大家講講跳表的由來與實(shí)現(xiàn),感興趣的小伙伴可以了解一下
    2023-06-06
  • MyBatis通過BATCH批量提交的方法

    MyBatis通過BATCH批量提交的方法

    今天小編就為大家分享一篇關(guān)于MyBatis通過BATCH批量提交的方法,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2018-12-12
  • mybatis 如何判斷l(xiāng)ist集合是否包含指定數(shù)據(jù)

    mybatis 如何判斷l(xiāng)ist集合是否包含指定數(shù)據(jù)

    這篇文章主要介紹了mybatis 判斷l(xiāng)ist集合是否包含指定數(shù)據(jù)的操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • SpringBoot+Idea熱部署實(shí)現(xiàn)流程解析

    SpringBoot+Idea熱部署實(shí)現(xiàn)流程解析

    這篇文章主要介紹了SpringBoot+Idea熱部署實(shí)現(xiàn)流程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-11-11

最新評論

巴南区| 修武县| 绍兴县| 焉耆| 苍山县| 枣强县| 沙坪坝区| 读书| 鸡西市| 孝昌县| 延安市| 台东市| 邯郸市| 永登县| 白朗县| 韶关市| 秭归县| 鞍山市| 皮山县| 隆回县| 冷水江市| 高邮市| 奈曼旗| 睢宁县| 固安县| 扶风县| 驻马店市| 山东省| 新乡市| 东乌珠穆沁旗| 姜堰市| 汶川县| 正镶白旗| 米泉市| 安国市| 湖口县| 观塘区| 南宫市| 乾安县| 绍兴市| 大足县|