SpringBoot 自定义异常

it2022-05-05  220

1、创建一个 类,继承要捕获的异常

package com.ym.springboot.exception; @SuppressWarnings("serial") public class BusinessException extends RuntimeException{ private String code; private String msg; public BusinessException(String code, String msg) { super(); this.code = code; this.msg = msg; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }

 2、创建一个异常捕获类,在类上标记@ControllerAdvice注解,标记该注解后,该类中的方法作用在所有@GetMapping注解的方法上,捕获不同的类型的异常。

package com.ym.springboot.exception; import java.util.HashMap; import java.util.Map; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice public class ControllerException { /** * 全局捕获异常 * @param ex * @return */ @ResponseBody @ExceptionHandler(value=Exception.class) public Map<String,Object> errorHander(Exception e){ Map<String,Object> map = new HashMap<String,Object>(); map.put("code", -1); map.put("msg", e.getMessage()); return map; } /** * 自定义类型异常捕获 * @param e * @return */ @ResponseBody @ExceptionHandler(value=BusinessException.class) public Map<String,Object> errorHander(BusinessException e){ Map<String,Object> map = new HashMap<String,Object>(); map.put("code", e.getCode()); map.put("msg", e.getMsg()); return map; } }

3、创建Contrller类,测试抛出异常

package com.ym.springboot.controller; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import com.ym.springboot.exception.BusinessException; @RestController public class HelloController { /** * 抛出全局异常 * @return */ @GetMapping("exception") public String exception() { int a = 1/0; return error; } /** * 抛出自定义运行时异常 * @return */ @GetMapping("businessException") public String businessException() { throw new BusinessException("-100", "用户名密码错误!"); } }

 

 4、测试


最新回复(0)