SpringBoot全局异常处理,返回http状态码500 或 json

1. 自定义异常

	public class SystemException extends RuntimeException{
	    private static final long serialVersionUID = 1L;
	    public SystemException(String message){
	        super(message);
	    }
	
	    public SystemException(Throwable cause)
	    {
	        super(cause);
	    }
	
	    public SystemException(String message,Throwable cause)
	    {
	        super(message,cause);
	    }
	}

2. 异常处理

返回错误状态码。说白了就是返回 ResponseEntity 对象,话不多说直接看代码

	@RestControllerAdvice 
	public class SystemExceptionHandler {
	// Result 是自己定义的统一返回格式
    
    // 处理自定义异常
    @ExceptionHandler(SystemException.class)
    public ResponseEntity<Result<?>> handlerRException(SystemException e) {
        HttpStatus httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
        return new ResponseEntity<>(Result.error(e.getMessage()), httpStatus);
    }
    
    // 返回json格式
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e) {
        log.error(e.getMessage(), e);
        return Result.error(e.getMessage());
    }

你可能感兴趣的:(spring,boot,http,json)