电子商务网站建设卷子,张家港公司网站建设,海沧网站建设,呼和浩特企业网站排名优化目录 前言WebResponseExceptionTranslator自定义异常处理1、自定义我们响应实体类2、定义响应结果枚举类3、自定义异常转换类4、配置自定义异常转换器5、测试 前言
Spring Security OAuth2 认证失败的格式如下
{error: unsupported_grant_type,error: unsupported_grant_type,error_description: Unsupported grant type: refresh_token1
}这个返回是很不友好的特别是在前后端分离的时候前端一般是根据我们的返回码进行处理所以我们还得自定义我们的异常处理
WebResponseExceptionTranslator
在 AuthorizationServerEndpointsConfigurer端点配置类有一个 WebResponseExceptionTranslator异常转换器。
WebResponseExceptionTranslator只有一个translate方法很明显这个方法就是用来转换异常的
public interface WebResponseExceptionTranslatorT {ResponseEntityT translate(Exception e) throws Exception;}它就是专门用于处理异常转换的我们要自定义异常很简单创建一个类来实现WebResponseExceptionTranslator接口然后进行配置即
自定义异常处理
1、自定义我们响应实体类
定义一个我们需要格式的响应实体类这个实体类我们以json的格式返回
/*** 统一的返回实体*/
Data
NoArgsConstructor
public class MyResponseResultT {/*** 响应码*/private String code;/*** 响应结果消息*/private String msg;/*** 响应数据*/private T data;protected MyResponseResult(String code, String msg, T data) {this.code code;this.msg msg;this.data data;}public static T MyResponseResultT failed(String resultCode, String resultMsg) {return new MyResponseResultT(resultCode, resultMsg, null);}public static T MyResponseResultT failed(String message) {return new MyResponseResultT(ResultCode.FAILED.getCode(), message, null);}public static T MyResponseResultT failed(T data) {return new MyResponseResultT(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMsg(), data);}}2、定义响应结果枚举类
/*** 响应结果枚举*/
Getter
AllArgsConstructor
public enum ResultCode {SUCCESS(200, 操作成功),FAILED(500, 操作失败),AUTH_FAIL(10001, 认证失败),INVALID_TOKEN(10002, token无效),NONSUPPORT_GRANT_TYPE(10003, 授权类型不支持),;private final String code;private final String msg;}3、自定义异常转换类
/*** 自定义异常转换*/
Slf4j
public class MyExtendOAuth2ResponseExceptionTranslator implements WebResponseExceptionTranslator {public static final int FAIL_CODE 500;Overridepublic ResponseEntity translate(Exception e) throws Exception {log.error(认证服务器认证异常{}, e.getMessage());//对异常进行转换if (e instanceof UnsupportedGrantTypeException){return ResponseEntity.status(FAIL_CODE).contentType(MediaType.APPLICATION_JSON).body(MyResponseResult.failed(ResultCode.NONSUPPORT_GRANT_TYPE.getCode(), ResultCode.NONSUPPORT_GRANT_TYPE.getMsg()));}if (e instanceof InvalidTokenException) {return ResponseEntity.status(FAIL_CODE).contentType(MediaType.APPLICATION_JSON).body(MyResponseResult.failed(ResultCode.INVALID_TOKEN.getCode(),ResultCode.INVALID_TOKEN.getMsg()));}return ResponseEntity.status(FAIL_CODE).contentType(MediaType.APPLICATION_JSON).body(MyResponseResult.failed(ResultCode.AUTH_FAIL.getCode(),ResultCode.AUTH_FAIL.getMsg()));}}4、配置自定义异常转换器
在AuthorizationServerConfig配置文件的configure(AuthorizationServerEndpointsConfigurer endpoints)方法加下下面这行配置即可
//指定异常转换器endpoints.exceptionTranslator(new MyExtendOAuth2ResponseExceptionTranslator());5、测试
使用一个不存在的grant_type请求/oauth/token已经返回我们自定义的异常响应了
{code: 10003,msg: 授权类型不支持,data: null
}