spring 使用 JSON 处理安全错误
spring security error handling with JSON
我正在尝试处理来自 spring-security
的异常错误,并且我在我的 web.xml
中使用了以下标签
example:
<error-page>
<error-code>403</error-code>
<location>/test2</location>
</error-page>
如果发生错误编号 403,那么我想调用一个控制器来处理这些错误,并以 json
格式 return 它们。
所以我想知道我是否可以在 web.xml
中定义多个错误代码
示例:
<error-page>
<error-code>403,404,401</error-code>
<location>/test2</location>
</error-page>
without defining a new
<error-page>
....
</error-page> . ?
第二个问题:如何将错误信息发送到我的控制器以给出正确的错误消息?
您必须定义多个错误页面才能实现此目的。
此外,您可以将错误代码传递给您的 spring 控制器,您可以在那里管理错误。
您应该能够使用 @ControllerAdvice
来处理此类异常。
@ControllerAdvice
public class MyControllerExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<Error> notFoundHanlder(NoHandlerFoundException ex) {
// 404 Your logic here.
}
@ExceptionHandler(HttpUnauthorizedException.class)
public ResponseEntity<Error> notAuthenticatedHanlder(HttpUnauthorizedException ex) {
// 401 Your logic here.
}
//so on.......
}
谢谢大家的建议,但我已经使用以下方法解决了我的问题:
在web.xml
<error-page>
<location>/controllerName</location>
</error-page>
然后使用以下代码获取错误号和错误信息:
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
String exceptionMessage = getExceptionMessage(throwable, statusCode);
我正在尝试处理来自 spring-security
的异常错误,并且我在我的 web.xml
example:
<error-page>
<error-code>403</error-code>
<location>/test2</location>
</error-page>
如果发生错误编号 403,那么我想调用一个控制器来处理这些错误,并以 json
格式 return 它们。
所以我想知道我是否可以在 web.xml
中定义多个错误代码
示例:
<error-page>
<error-code>403,404,401</error-code>
<location>/test2</location>
</error-page>
without defining a new
<error-page>
....
</error-page> . ?
第二个问题:如何将错误信息发送到我的控制器以给出正确的错误消息?
您必须定义多个错误页面才能实现此目的。
此外,您可以将错误代码传递给您的 spring 控制器,您可以在那里管理错误。
您应该能够使用 @ControllerAdvice
来处理此类异常。
@ControllerAdvice
public class MyControllerExceptionHandler {
@ExceptionHandler(NoHandlerFoundException.class)
public ResponseEntity<Error> notFoundHanlder(NoHandlerFoundException ex) {
// 404 Your logic here.
}
@ExceptionHandler(HttpUnauthorizedException.class)
public ResponseEntity<Error> notAuthenticatedHanlder(HttpUnauthorizedException ex) {
// 401 Your logic here.
}
//so on.......
}
谢谢大家的建议,但我已经使用以下方法解决了我的问题:
在web.xml
<error-page>
<location>/controllerName</location>
</error-page>
然后使用以下代码获取错误号和错误信息:
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
String exceptionMessage = getExceptionMessage(throwable, statusCode);