简体   繁体   English

Spring引导@ExceptionHandler以html的形式返回响应

[英]Spring boot @ExceptionHandler return the response as html

I'am biggner to Spring boot When an exception is thrown I get the response as HTML while I need it as JSON. 我对Spring启动比较大当抛出异常时,我将响应视为HTML,而我需要它作为JSON。

service response 服务响应

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>

this is the exception The environment must be QAT2, PSQA or DEVSTAGE4 I need it as JSON response without writing custom exception handler class like this: 这是异常环境必须是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"
}

it was working as expected previously but I had do some changes that case to this Controller 它之前的工作正如预期的那样,但我已经对这个控制器进行了一些更改

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");
    }

}

} }

Model 模型

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;}
}

Application 应用

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);
    }
}

Remove @ResponseBody from above class scope and be aware of url values they are should be started with '/' not just typing the url, so instead of typing 从上面的类范围中删除@ResponseBody并注意它们应该以'/'开头的url值,而不仅仅是键入url,所以不要键入

@RequestMapping(value = "createMember", method = RequestMethod.POST)

this should be 这应该是

@RequestMapping(value = "/createMember", method = RequestMethod.POST)

Or even better if you annotated it with post directly like the following 或者更好的是如果你直接用post注释它,如下所示

@PostMapping(value = "/createMember")

Same thing GET AND PUT etc 同样的事情GET AND PUT

Your handler catches only IllegalStateException but not the IllegalArgumentException that is thrown: 您的处理程序仅捕获IllegalStateException,但不捕获抛出的IllegalArgumentException:

   @ExceptionHandler(IllegalStateException.class)
    void handleIllegalStateException(IllegalStateException e, HttpServletResponse response) throws IOException {
        response.sendError(HttpStatus.BAD_REQUEST.value());
    }

Those are both RuntimeExceptions. 这些都是RuntimeExceptions。 To catch both in the same handler, you could try to replace it to: 要在同一个处理程序中捕获它们,您可以尝试将其替换为:

   @ExceptionHandler(RuntimeException.class)
    void handleIllegalStateException(IllegalStateException e, HttpServletResponse response) throws IOException {
        response.sendError(HttpStatus.BAD_REQUEST.value());
    }

Actually, that would catch all RuntimeExceptions thrown by this controller. 实际上,这将捕获此控制器抛出的所有 RuntimeExceptions。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM