本节讨论如何使用Spring的异常处理机制,当我们程序出现错误时,以相同的一种格式,把错误信息返回给客户端
1、创建一些自定义异常
public class TipsException extends Exception {
private static final long serialVersionUID = 2784987176856514682L; public TipsException(String string) {
super(string);
}}
2、使用@RestControllerAdvice创建一个异常处理的RESTful控制器,当其他控制器抛出异常时,会被这个控制器截获并处理
@RestControllerAdvice
public class ExceptionController { @ExceptionHandler(TipsException.class)
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
public AppResult tips(TipsException e) {
return new AppResult().error(e.getMessage());
}
@ExceptionHandler()
@ResponseStatus(HttpStatus.ALREADY_REPORTED)
public AppResult spittleNotFound(Exception e) {
return new AppResult().error("内部错误!请联系系统管理员!" + e.getClass().getTypeName() + e.getMessage());
}}
这里的异常处理会返回一个和普通控制器一样的AppResult对象,保证任何时候返回给客户端的值都是统一格式的
3、运行测试