Spring Boot异常处理

一.异常类
package com.chx.springboot.exception;
 
 
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
 
 
import java.util.HashMap;
import java.util.Map;
 
 
@ControllerAdvice
public class ExceptionHandler {
    //捕获运行时异常
    @org.springframework.web.bind.annotation.ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public Map<String,Object> exceHandler() {
        Map<String, Object> map = new HashMap<>();
        map.put("error", "500");
        map.put("msg", "您好,服务器暂时出现异常,请稍后重试");
        return map;
    }
}
 
二.控制层模拟异常
package com.chx.springboot.controller;
 
 
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
 
@RestController
@RequestMapping("/hello")
public class MyController {
    @RequestMapping("/sayHello")
    public String sayHello(){
        //模拟运行时异常
        int result=5/0;
        return "hello springboot";
    }
}
 
三.运行结果
 
 
原文地址:https://www.cnblogs.com/chx9832/p/12017625.html