简体   繁体   中英

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.

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:

{
   "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

@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

@PostMapping(value = "/createMember")

Same thing GET AND PUT etc

Your handler catches only IllegalStateException but not the IllegalArgumentException that is thrown:

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

Those are both 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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