关于统一处理Error

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bloodylzy/article/details/82143675

Spring中存在统一处理抛出错误的场景

@ControllerAdvice 

这个是来切Controller的,该注解是放置在class上面的

在类中,关于方法体,

@ExceptionHandler(Exception.class)

这个注解,表示被这个注解标记的会来处理Exception,而被controller抛出的Exception错误是会被这个注解 handle 掉

那么这里我们就可以这样做:


import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.security.oauth2.common.exceptions.UnauthorizedUserException;
import org.springframework.web.bind.MethodArgumentNotValidException;
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;


@ControllerAdvice
@Slf4j
@Order(Ordered.HIGHEST_PRECEDENCE + 50)
public class GlobalExceptionHandler {


	@ExceptionHandler(Exception.class)
	@ResponseBody
	@ResponseStatus(HttpStatus.OK)
	public ApiResponse defaultExceptionHandler(Exception e) {
		return ResponseUtil.fail(String.valueOf(ErrorCode.UNKNOWN.getRetCode()), ErrorCode.UNKNOWN.getRetMsg());
	}


}

这里就是一个处理controller的类

猜你喜欢

转载自blog.csdn.net/bloodylzy/article/details/82143675