spring 中的异常处理机制可以处理大部分异常,如果想要获取 message 以外的异常信息,需要其他处理,自定义异常来处理
自定义异常步骤:
1、定义异常类,实现Exception() 或 RuntimeException()
package com.llangzh.exception;
public class UserNotExistException extends RuntimeException{
private static final long serialVersionUID = 1L;
private String id;
public UserNotExistException(String id) {
super("用户出现自定义异常");
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
2、自定义异常处理的 Handler
package com.llangzh.handler;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import com.llangzh.exception.UserNotExistException;
@ControllerAdvice
public class MyExceptionHandler {
@ExceptionHandler(UserNotExistException.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, Object> userNotExistExceptionHandler(UserNotExistException ex){
Map<String, Object> handlerMap = new HashMap<String, Object>();
handlerMap.put("id", ex.getId());
handlerMap.put("message", ex.getMessage());
return handlerMap;
}
}
注解作用:
@ControllerAdvice:标明此类用于处理 Controller 抛出的异常
@ExceptionHandler:指定方法要处理的异常
@ResponseBody:返回json
@ResponseStatus:指定返回的 http 的状态码
3、使用自定义异常处理
package com.llangzh.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.llangzh.exception.UserNotExistException;
@RestController()
public class UserController {
@GetMapping("/{id:\\d+}")
public String testException(@PathVariable String id) throws Exception {
throw new UserNotExistException(id);
}
}
测试:
返回结果:{"id":"1","message":"用户出现自定义异常"}