springboot整合全局捕获异常

1.全局捕获异常处理器

springboot整合全局捕获异常_第1张图片
代码如下:

package com.example.exceptiondemo.error;

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;

/**
 * create by
 *
 * @Author luozhiyuan
 * @qq [email protected]
 * @on 2019-06-30.
 * @time 11:17
 */
@ControllerAdvice("com.example.exceptiondemo.controller")
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Map errorResult(){
        Map errorResultMap = new HashMap<>();
        errorResultMap.put("errorCode","500");
        errorResultMap.put("errorMsg","全局捕获异常!");
        return errorResultMap;
    }
}

2.抛出异常的controller

springboot整合全局捕获异常_第2张图片

package com.example.exceptiondemo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * create by
 *
 * @Author luozhiyuan
 * @qq [email protected]
 * @on 2019-06-30.
 * @time 14:48
 */
@RestController
public class ErrorController {
    @RequestMapping("/getUser")
    public String getUser(Integer i){
        Integer j = 1 / i;
        return "success"+j;
    }
}

你可能感兴趣的:(springBoot)