【发布时间】:2022-01-30 15:02:54
【问题描述】:
我希望当遇到错误时,用户会收到对他的 http 调用的异常响应。 错误确实被捕获,显示在 spring 日志中,但没有返回给用户。 为什么?
我的方法:
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) {
try {
// Check for authorization header existence.
String header = request.getHeader(JwtConstant.AUTHORIZATION_HEADER_STRING);
if (header == null || !header.startsWith(JwtConstant.TOKEN_BEARER_PREFIX)) {
chain.doFilter(request, response);
return;
}
// Validate request..
UsernamePasswordAuthenticationToken authorization = authorizeRequest(request);
SecurityContextHolder.getContext().setAuthentication(authorization);
chain.doFilter(request, response);
} catch (Exception e) {
SecurityContextHolder.clearContext();
throw new InternalServerErrorException("Erreur sur le filtre interne -> " + e.toString()); // Should return this to the user
}
}
日志中的错误:
.common.application.exception.InternalServerErrorException: Erreur sur le filtre interne ->
.common.application.exception.InternalServerErrorException: Erreur lors du authorizeRequest
错误处理程序:
@ControllerAdvice
public class ApiResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
String typeDateFormat = "yyyy-MM-dd HH:mm:ss";
...
@ExceptionHandler(InternalServerErrorException.class)
public final ResponseEntity<ExceptionResponse> handleInternalServerErrorException(InternalServerErrorException ex,
WebRequest request) {
ExceptionResponse exceptionResponse = new ExceptionResponse(
new SimpleDateFormat(typeDateFormat).format(new Date()), ex.getMessage(),
request.getDescription(false), "500");
return new ResponseEntity<>(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
InternalServerErrorException.java
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public class InternalServerErrorException extends RuntimeException {
private static final long serialVersionUID = 1L;
public InternalServerErrorException(String exception) {
super(exception);
}
}
ExceptionResponse.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class ExceptionResponse {
private String date;
private String message;
private String uri;
private String status;
}
用户收到 403.. 我不知道为什么,但应该收到我抛出的错误,没有任何正文..
InternalServerException 在 try/catch 之外起作用..
【问题讨论】:
标签: java spring spring-boot spring-mvc spring-security