spring boot中的自定义异常和异常处理器

 

默认情况下,Spring Boot提供了一个/error的控制器以合理方式处理所有错误的映射,客户端访问出错返回一个json,浏览器访问会返回一个HTML。然而很多时候,无论是客户端还是web端都需要服务器返回一个json,用于前端解析并以自己的方式展示给用户看。这时候就要自定义异常处理器。同时你也可以自定义你的异常类。 
本文只分享怎么给自定义异常写处理器,如果你想给已有的异常写处理你可以看http://blog.csdn.net/neosmith/article/details/51090509


自定义异常

你可以自定义普通的Exception,也可以自定义RuntimeException。下面的例子比较简单,你也可以在你自定义的exception中写你的逻辑。

自定义Exception

public class MyException extends Exception{

    private static final long serialVersionUID = -5519743897907627214L;

    public MyException(String message) {
        super(message);
    }

}

自定义RuntimeException

public class MyRuntimeException extends RuntimeException {

    private static final long serialVersionUID = -6925278824391495117L;

    public MyRuntimeException(String message) {
        super(message);
    }

}

异常处理器

@ControllerAdvice拦截异常,@ExceptionHandler指定处理哪种异常(可指定多个),@ResponseStatus指定返回的http状态码(具体可查看HttpStatus这个类),@ControllerAdvice+@ResponseBody可换成@RestControllerAdvice.

@ControllerAdvice
@ResponseBody
public class MyExceptionHandler {

    @ExceptionHandler(MyException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> handlerMyException(MyException ex) {
        Map<String,Object> result = new HashMap<>();
        result.put("message", ex.getMessage());
        result.put("error type", "MyException");
        return result;
    }

    @ExceptionHandler(MyRuntimeException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Map<String, Object> handlerMyRuntimeException(MyRuntimeException ex) {
        Map<String,Object> result = new HashMap<>();
        result.put("message", ex.getMessage());
        result.put("error type", "MyRuntimeException");
        return result;
    }
}

注意ControllerAdvice只能捕获到全局Controller范围内的,之外的异常就无法捕获了,如filter中抛出异常的话,ControllerAdvice是无法捕获的。这时候你就需要按照官方文档中的方法,实现 ErrorController并注册为controller。

测试

写个controller来测试

@RestController
@RequestMapping("/exception")
public class ExceptionTestController {

    @GetMapping("/{id}")
    public String test(@PathVariable(name="id") Integer id) throws MyException {

        if(id == 1) {
            throw new MyException("id不能为1");
        }else if(id == 2) {
            throw new MyRuntimeException("id不能为2");
        }

        return "SUCCESS";
    }

}

在浏览器中输入http://127.0.0.1:8080/exception/1结果为 

“message”: “id不能为1”, 
“error type”: “MyException” 

在浏览器中输入http://127.0.0.1:8080/exception/2结果为 

“message”: “id不能为2”, 
“error type”: “MyRuntimeException” 

在浏览器中输入http://127.0.0.1:8080/exception/3结果为 
SUCCESS

猜你喜欢

转载自blog.csdn.net/qq_35568099/article/details/82940821
今日推荐