Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring boot@ExceptionHandler以html形式返回响应_Java_Spring_Spring Boot_Tomcat_Servlets - Fatal编程技术网

Java Spring boot@ExceptionHandler以html形式返回响应

Java Spring boot@ExceptionHandler以html形式返回响应,java,spring,spring-boot,tomcat,servlets,Java,Spring,Spring Boot,Tomcat,Servlets,当抛出异常时,我对Spring boot更感兴趣,我得到的响应是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 Er

当抛出异常时,我对Spring boot更感兴趣,我得到的响应是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>
这是工作的预期之前,但我做了一些改变,这种情况下,这个 控制器

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

处理程序只捕获IllegalStateException,而不捕获抛出的IllegalArgumentException:

   @ExceptionHandler(IllegalStateException.class)
    void handleIllegalStateException(IllegalStateException e, HttpServletResponse response) throws IOException {
        response.sendError(HttpStatus.BAD_REQUEST.value());
    }
这些都是运行时异常。要在同一个处理程序中捕获这两个,可以尝试将其替换为:

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

实际上,这将捕获此控制器引发的所有运行时异常。

从上述类范围中删除
@ResponseBody
,并注意它们的url值应该以“/”开头,而不仅仅是键入url,所以不要键入

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

这应该是

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

或者,如果你像下面这样直接用post对它进行注释,那就更好了

@PostMapping(value=“/createMember”)


同样的事情
GET
PUT
etc

尝试使用此代码
response.senderro(HttpStatus.BAD_REQUEST)
而不是
response.senderro(HttpStatus.BAD_REQUEST.value())
@Generic这也不起作用,我在控制台中得到了异常,但仍然是同一问题,控制器确实捕获了异常,但他以HTML形式返回错误,我可以在响应中看到异常,但如果这有帮助,我需要它作为jsonSee:@RequestMapping(value=“createMember”,method=RequestMethod.POST,products=“application/json”)
   @ExceptionHandler(RuntimeException.class)
    void handleIllegalStateException(IllegalStateException e, HttpServletResponse response) throws IOException {
        response.sendError(HttpStatus.BAD_REQUEST.value());
    }