17,统一异常处理类

用于项目中对异常的统一捕获和处理=

package com.yuiyu.project2.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class TestController {
    @RequestMapping("/error")
    public String  err(){ int a=10/0;  //异常
        System.out.println(a);
       return "111";
    }
}

捕获异常

package com.yuiyu.project2.excetion;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.HandlerMethod;
@ControllerAdvice
public class ErrorControllerAdvice {
    @ExceptionHandler
    public void handlerError(Exception ex, HandlerMethod handlerMethod){
        System.out.println("统一异常处理类");
        System.out.println(ex.getMessage());//异常的内容
        System.out.println(handlerMethod.getBean().getClass());//出现异常的类
        System.out.println(handlerMethod.getMethod().getName());
    }
}

你可能感兴趣的:(17,统一异常处理类)