There's a piece of code that throws a exception:
java.lang.RuntimeException: cn.dev33.satoken.exception.NotLoginException: Invalid Token:ldxutBDDKBEDa9LjWNTKLFbW7g7B86qU
.
And then it goes into handleRuntimeException
rather than returnNotLoginException
method.
@Component
@Slf4j
@Primary
public class MyLockKeyBuilder extends DefaultLockKeyBuilder {
@Override
public String buildKey(MethodInvocation invocation, String[] definitionKeys) {
String key = super.buildKey(invocation, definitionKeys);
Object loginId = StpUtil.getLoginId(); // throw a exception
key = loginId.toString();
return key;
}
}
@ControllerAdvice(basePackages = "com.test")
@Slf4j
public class GraceExceptionHandlerApp {
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ExceptionHandler(value = NotLoginException.class)
@ResponseBody
public JSONObject returnNotLoginException(NotLoginException e) {
e.printStackTrace();
String message = e.getMessage();
ResponseStatusEnum failed = ResponseStatusEnum.UNAUTHORIZED;
failed.setMsg(message);
return ZheliResult.exception(failed);
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ExceptionHandler(RuntimeException.class)
@ResponseBody
public JSONObject handleRuntimeException(RuntimeException e, HttpServletRequest request)
{
String requestURI = request.getRequestURI();
return ZheliResult.errorCustom(ResponseStatusEnum.FAILED);
}
...
}
I want it goes into the returnNotLoginException
method, could anyone tell me how to do it?
CodePudding user response:
NotLoginException
is the inner exception of your RuntimeException
. If you want your controller advice to handle it, catch the RuntimeException buildKey and throw its inner exception.
CodePudding user response:
Based on your question,
java.lang.RuntimeException: cn.dev33.satoken.exception.NotLoginException: Invalid Token:
Your exception type is java.lang.RuntimeException
& cause of exception is NotLoginException
.
Controller advice will invoke respective method when type of exception matches & not cause of exception.
So if you really want to invoke returnNotLoginException
, then you need to throw NotLoginException
in your logic instead of throwing RuntimeException
.
Something like:
..
throw new NotLoginException("exception"); //in your StpUtil.getLoginId();
..