《SpringBoot 入门到精通 第四讲 全局异常捕获》

SpringBoot 全局异常捕获

有下面一段代码:

package com.learning.helloworld.api;

@RestController
@RequestMapping("/member")
@EnableAutoConfiguration
public class MemberController {

    @RequestMapping("/getUser")
    public  String getuser(int i ){
        int j = 1/i;
        return  "scuess" + j;
    }

}

正常访问:http://localhost:8089/member/getUser?i=10

《SpringBoot 入门到精通 第四讲 全局异常捕获》_第1张图片

异常访问:http://localhost:8089/member/getUser?i=0

《SpringBoot 入门到精通 第四讲 全局异常捕获》_第2张图片

 

当他的访问出现异常的时候就会把 这段文字 展现给玩家:

以前的处理方式 是加上 try .....catch{}

《SpringBoot 入门到精通 第四讲 全局异常捕获》_第3张图片

《SpringBoot 入门到精通 第四讲 全局异常捕获》_第4张图片

 

使用  try ...catch 需要手动添加给 又可以能出现异常的位置 ,

这时候 SpringBoot 的全局异常捕获 就显现出来了。 使用 AOP 技术,采用异常通知,把相应的错误 信息 返回给用户

具体操作 

新建一个处理异常错误的类  class

 package com.learning.helloworld;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

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

///全局捕获异常 分为两种
/// 1. 捕获异常返回 json 格式 信息
/// 2. 捕获页面错误 比如找不到页面,

@ControllerAdvice(basePackages = "com.learning.helloworld")
public class GlobalErr {

    @ResponseBody //捕获异常返回 json 格式 信息
    @ExceptionHandler(RuntimeException.class)
    public Map errorResoult(){
        Map errorMap = new HashMap();
        errorMap.put("errorCode", "500");
        errorMap.put("errorMessage", "系统错误");
        return  errorMap;
    }
}

然后 报错的地方就不用管了,有错误 会自己触发 

《SpringBoot 入门到精通 第四讲 全局异常捕获》_第5张图片

《SpringBoot 入门到精通 第四讲 全局异常捕获》_第6张图片

你可能感兴趣的:(《SpringBoot,入门到精通,第三讲,静态资源》,SpringBoot,入门到精通,第四讲,全局异常捕获)