我有一个Spring控制器,它可能在某个时候抛出运行时异常:
{% extends 'nowandthen/base.html' %}
{% load staticfiles %}
{% block title_block %}
Add self
{% endblock %}
{% block body_block %}
<h1>Add a Comment</h1>
<div>
<form id="comment_form" method="post" action="{% url 'nowandthen:add_comment' comment_id%}" enctype="multipart/form-data" >
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="Add Comment" />
</form>
</div>
{% endblock %}
当我请求该URI时,JSON不包括异常名称(“运行时异常”):
https://login.microsoftonline.com/<tenantId>/oauth2/token
是否可以将其包含在返回的JSON中? 谢谢!
答案 0 :(得分:1)
我认为您可以通过扩展DefaultErrorAttributes并提供要显示在返回的JSON中的属性的自定义列表来实现。例如,以下内容提供了针对字段错误的自定义错误响应:
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.context.MessageSource;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.context.request.WebRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
public class ResolvedErrorAttributes extends DefaultErrorAttributes {
private MessageSource messageSource;
public ResolvedErrorAttributes(MessageSource messageSource) {
this.messageSource = messageSource;
}
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, includeStackTrace);
resolveBindingErrors(errorAttributes);
return errorAttributes;
}
private void resolveBindingErrors(Map<String, Object> errorAttributes) {
List<ObjectError> errors = (List<ObjectError>) errorAttributes.get("errors");
if (errors == null) {
return;
}
List<String> errorMessages = new ArrayList<>();
for (ObjectError error : errors) {
String resolved = messageSource.getMessage(error, Locale.US);
if (error instanceof FieldError) {
FieldError fieldError = (FieldError) error;
errorMessages.add(fieldError.getField() + " " + resolved + " but value was " + fieldError.getRejectedValue());
} else {
errorMessages.add(resolved);
}
}
errorAttributes.put("errors", errorMessages);
}
}
在此tutorial中,您可以找到有关Spring Boot自定义错误响应的更多详细信息。