使用SpringMVC实现全局异常处理 - 实战

使用SpringMVC框架有很多便利的地方,本文主要演示其对全局异常的拦截处理,具体使用@ControllerAdvice标签和实现ResponseBodyAdvice接口来完成。

代码实现

  1. 定义全局异常处理类

其中beforeBodyWrite()方法可以对正常返回的结果进行再次处理。

package com.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
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.servlet.mvc.method.annotation.ResponseBodyAdvice;

@Slf4j
@ResponseBody
@ControllerAdvice
public class GlobalResultHandle implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, 
				    MediaType selectedContentType, Class selectedConverterType, 
				    ServerHttpRequest request, ServerHttpResponse response) {
        if (selectedContentType.equals(MediaType.APPLICATION_OCTET_STREAM)) {
            return body;
        } else if (body instanceof Result) {
            return body;
        } else if (body instanceof ResponseEntity) {
            return body;
        } else {
            // TODO
        }
        return new Result<>(body);
    }

    @ExceptionHandler({Exception.class})
    public Result<Object> handleException(Exception e) {
        log.error("请求异常,原因:{}", e.getMessage());
        return new Result<>(-1, e.getMessage());
    }

}
  1. 定义返回结果类
package com.demo;

import lombok.Data;

import java.io.Serializable;

@Data
public class Result<T> implements Serializable {

    private int code;

    private T data;

    private String msg = "成功";

    public Result() {}

    public Result(T body) {
        this.setData(body);
    }
    
	public Result(int code, String msg) {
        this.setCode(code);
        this.setMsg(msg);
    }

}

你可能感兴趣的:(其他,springmvc,exception,java,后端)