我对Spring启动比较大当抛出异常时,我将响应作为HTML获取,而我需要它作为JSON。
服务响应
HTTP/1.1 500
Content-Type: text/html;charset=UTF-8
Content-Language: en-US
Content-Length: 345
Date: Mon, 28 May 2018 16:13:06 GMT
Connection: close
<html><body><h1>Whitelabel Error Page</h1><p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p><div id='created'>Mon May 28 19:13:06 EEST 2018</div><div>There was an unexpected error (type=Internal Server Error, status=500).</div><div>The environment must be QAT2,PSQA or DEVSTAGE4</div></body></html>
这是异常环境必须是QAT2,PSQA或DEVSTAGE4我需要它作为JSON响应而不编写自定义异常处理程序类,如下所示:
{
"timestamp" : 1413313361387,
"exception" : "java.lang.IllegalArgumentException",
"status" : 500,
"error" : "internal server error",
"path" : "/greet",
"message" : "The environment must be QAT2,PSQA or DEVSTAGE4"
}
它之前的工作正如预期的那样,但我已经做了一些改变 的控制器
package main.controller;
@RestController
@RequestMapping("/api")
public class API {
private final APIService apiService;
@Autowired
public API(APIService offersService) {this.apiService = offersService;}
@ExceptionHandler(IllegalArgumentException.class)
void handleIllegalStateException(IllegalArgumentException e, HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.FORBIDDEN.value());
}
@PostMapping(value = "/createMember", produces = "application/json")
public ResponseEntity createMembers(@Valid @RequestBody APIModel requestBody) throws IllegalArgumentException {
validatePrams();
apiService.fillMembersData();
return ResponseEntity.ok(HttpStatus.OK);
}
private void validatePrams() throws IllegalArgumentException {
if (APIModel.getEnvironment() == null || (!APIModel.getEnvironment().equalsIgnoreCase("QAT2")
&& !APIModel.getEnvironment().equalsIgnoreCase("PSQA")
&& !APIModel.getEnvironment().equalsIgnoreCase("DEVSTAGE4"))) {
throw new IllegalArgumentException("The environment must be QAT2,PSQA or DEVSTAGE4");
}
}
}
模型
package main.model;
@Entity
@Table(name = "APIModel")
public class APIModel {
@Id
@Column(name = "environment", nullable = false)
@NotNull
private static String environment;
@Column(name = "country", nullable = false)
@NotNull
private static String country;
@Column(name = "emailTo", nullable = false)
@NotNull
private static String emailTo;
@Column(name = "plan", nullable = false)
@NotNull
private static String plan;
@Column(name = "paymentType", nullable = false)
@NotNull
private static String paymentType;
@Column(name = "numberOfUsers", nullable = false)
@NotNull
private static Integer numberOfUsers;
@Column(name = "program")
private static String program;
public APIModel(String environment, String country, String emailTo, String plan, String paymentType, Integer numberOfUsers, String program) {
APIModel.environment = environment;
APIModel.country = country;
APIModel.emailTo = emailTo;
APIModel.plan = plan;
APIModel.paymentType = paymentType;
APIModel.numberOfUsers = numberOfUsers;
APIModel.program = program;
}
public APIModel() {}
public static String getEnvironment() {return environment;}
public void setEnvironment(String environment) {APIModel.environment = environment;}
public static String getCountry() {return country;}
public static String getEmailTo() {return emailTo;}
public static String getPlan() {return plan;}
public static String getPaymentType() {return paymentType;}
public static Integer getNumberOfUsers() {return numberOfUsers;}
public static String getProgram() {return program;}
public void setProgram(String program) {APIModel.program = program;}
}
应用
package main;
@SpringBootApplication
public class MainClass {
static {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd'/'hh_mm_ss");
System.setProperty("current.date.time", dateFormat.format(new Date()));
System.setProperty("usr_dir", System.getProperty("user.dir") + "\\src\\logs");
}
public static void main(String[] args) {
SpringApplication.run(MainClass.class, args);
}
}
答案 0 :(得分:2)
从上面的类范围中删除grep
并注意它们应该以'/'开头的url值,而不仅仅是键入url,而不是输入
@ResponseBody
这应该是
@RequestMapping(value = "createMember", method = RequestMethod.POST)
如果您使用post直接注释它,甚至更好,如下所示
@RequestMapping(value = "/createMember", method = RequestMethod.POST)
同样的事情@PostMapping(value = "/createMember")
和GET
等
答案 1 :(得分:1)
您的处理程序仅捕获IllegalStateException,但不捕获抛出的IllegalArgumentException:
@ExceptionHandler(IllegalStateException.class)
void handleIllegalStateException(IllegalStateException e, HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.BAD_REQUEST.value());
}
这些都是RuntimeExceptions。要在同一个处理程序中捕获它们,您可以尝试将其替换为:
@ExceptionHandler(RuntimeException.class)
void handleIllegalStateException(IllegalStateException e, HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.BAD_REQUEST.value());
}
实际上,这会捕获此控制器抛出的所有 RuntimeExceptions。