Spring Boot Web应用出现异常时,如何自定义响应状态码和响应体中的数据?
我创建了一个网络应用程序,如果由于内部状态不佳而发生意外情况,它会抛出自定义异常。因此,触发错误的请求的响应主体类似于:
HTTP/1.1 500 Internal Server Error
{
"timestamp": 1412685688268,
"status": 500,
"error": "Internal Server Error",
"exception": "com.example.CustomException",
"message": null,
"path": "/example"
}
现在,我想更改状态代码并设置响应正文中的字段。我想到的一个解决方案是这样的:
@ControllerAdvice
class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
ErrorMessage handleBadCredentials(CustomException e) {
return new ErrorMessage("Bad things happened");
}
}
@XmlRootElement
public class ErrorMessage(
private String error;
public ErrorMessage() {
}
public ErrorMessage(String error) {
this.error = error;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
)
然而,这产生了(正如怀疑的那样)完全不同的 react :
HTTP/1.1 400 Bad Request
{
"error": "Bad things happened"
}
最佳答案
正如@zeroflagL 提到的,Spring Boot 在 org.springframework.boot.autoconfigure.web.DefaultErrorAttributes 中制作了“标准”错误响应主体。与您的需求类似,我想利用所有这些,但只是再增加一个由我的一些异常提供的“类型”字段。
我通过实现一个子类 DefaultErrorAttributes 的 Component 来做到这一点。 Spring Boot 自动拾取它并使用我的而不是默认值。
@Component
public class ExtendedErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(RequestAttributes requestAttributes,
boolean includeStackTrace) {
final Map<String, Object> errorAttributes =
super.getErrorAttributes(requestAttributes,
includeStackTrace);
final Throwable error = super.getError(requestAttributes);
if (error instanceof TypeProvider) {
final TypeProvider typeProvider = (TypeProvider) error;
errorAttributes.put("type", typeProvider.getTypeIdentifier());
}
return errorAttributes;
}
}
有了它,我得到了一个增强的 JSON 响应主体,例如
{
"timestamp": 1488058582764,
"status": 429,
"error": "Too Many Requests",
"exception": "com.example.ExternalRateLimitException",
"message": "DAILY_LIMIT: too many requests",
"path": "/api/lookup",
"type": "DAILY_LIMIT"
}
关于java - Spring Boot 自定义 http 错误响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26236811/
我正在尝试设置一个puppet节点,但rubygems似乎不正常。如果我通过它自己的二进制文件(/usr/lib/ruby/gems/1.8/gems/facter-1.5.8/bin/facter)在cli上运行facter,它工作正常,但如果我通过由rubygems(/usr/bin/facter)安装的二进制文件,它抛出:/usr/lib/ruby/1.8/facter/uptime.rb:11:undefinedmethod`get_uptime'forFacter::Util::Uptime:Module(NoMethodError)from/usr/lib/ruby
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer
是的,我知道最好使用webmock,但我想知道如何在RSpec中模拟此方法:defmethod_to_testurl=URI.parseurireq=Net::HTTP::Post.newurl.pathres=Net::HTTP.start(url.host,url.port)do|http|http.requestreq,foo:1endresend这是RSpec:let(:uri){'http://example.com'}specify'HTTPcall'dohttp=mock:httpNet::HTTP.stub!(:start).and_yieldhttphttp.shou
我想向我的Controller传递一个参数,它是一个简单的复选框,但我不知道如何在模型的form_for中引入它,这是我的观点:{:id=>'go_finance'}do|f|%>Transferirde:para:Entrada:"input",:placeholder=>"Quantofoiganho?"%>Saída:"output",:placeholder=>"Quantofoigasto?"%>Nota:我想做一个额外的复选框,但我该怎么做,模型中没有一个对象,而是一个要检查的对象,以便在Controller中创建一个ifelse,如果没有检查,请帮助我,非常感谢,谢谢
我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby1.9+ 关于ruby-主要:Objectwhenrun
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file