プロジェクト戦闘でのSpringboot2.Xグローバル例外処理

SpringBoot2.xオンライン教育プロジェクトでのグローバル例外処理

はじめに:SpringBoot2.Xグローバル例外処理について説明する

なぜグローバル例外を設定するのですか?

  • グローバルサーバーエラーシナリオ1/0、nullポインタなどには適していません。

構成上の利点

  • 統一されたエラーページまたはエラーコード
  • よりユーザーフレンドリー

Springboot2.Xはプロジェクトでグローバル例外をどのように構成しますか

  • クラスに注釈を付ける

    • @ControllerAdvice、jsonデータを返す必要がある場合、メソッドは@ResponseBodyを追加する必要があります
    • @RestControllerAdvice、デフォルトでjsonデータを返します。メソッドは@ResponseBodyを追加する必要はありません
  • ハンドラーを追加するメソッド

    • グローバルな例外をキャッチし、すべての不明な例外を処理します
    • @ExceptionHandler(value = Exception.class)

コントローラーレイヤー

@RestController
@RequestMapping("api/v1/test")
public class TestController {
    
    
 @GetMapping("list")
    public JsonData testExt(){
    
    
        int i =1 /0;
        return JsonData.buildSuccess("");
    }
}

ハンドルレイヤー

/**
 * 标记这是一个异常处理
 */
@RestControllerAdvice  //标记用于处理异常
//@ControllerAdvice
public class CustomExHandle {
    
    
    //处理json
    @ExceptionHandler(value = Exception.class)
    Object handleException(Exception e, HttpServletRequest request){
    
    
       return JsonData.buildError("服务端出问题",-2);
    }
}

jsonおよび非jsonデータを処理するための@RestControllerAdviceおよび@ControllerAdvice


SpringBoot2.xカスタムグローバル例外リターンページ

SpringBootを使用して例外ページとエラーページをカスタマイズし、実際の戦闘にジャンプします

カスタム例外インターフェースに戻るには、thymeleaf依存関係を導入する必要があります(必須ではありません。単純なhtmlインターフェースの場合は不要です)。

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

error.htmlエラーページを作成する

htmlページ

<!DOCTYPE html>
<!--在使用时需添加 xmlns:th="http://www/thymeleaf.org"-->
<html lang="en" xmlns:th="http://www/thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
这是一个自定义异常的界面

<!--获取到报错的信息 等,按需求获取所需的报错信息
    注:msg必须与hanlde层中自定义的一致
    e.getMessage() :报错的信息
    e.getClass()   :报错的类型
-->
<p th:text="${msg}"></p>
</body>
</html>

ハンドルレイヤー

/**
 * 标记这是一个异常处理
 */
//@RestControllerAdvice  //标记用于处理异常
@ControllerAdvice
public class CustomExHandle {
    
    
//    //处理json
//    @ExceptionHandler(value = Exception.class)
//    Object handleException(Exception e, HttpServletRequest request){
    
    
//       return JsonData.buildError("服务端出问题",-2);
//    }

    @ExceptionHandler(value = Exception.class)
    Object handleException(Exception e, HttpServletRequest request){
    
    
        ModelAndView modelAndView =new ModelAndView();
        modelAndView.setViewName("error.html");
        modelAndView.addObject("msg",e.getMessage());
        System.out.println(e.getMessage());
        return modelAndView;
    }
}

おすすめ

転載: blog.csdn.net/m0_49969111/article/details/118694253