Skip to content

Commit

Permalink
触发限流后的响应类型改成 application/json
Browse files Browse the repository at this point in the history
  • Loading branch information
klboke committed Mar 24, 2021
1 parent 899a7b3 commit 7b0dde4
Showing 1 changed file with 11 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,31 +3,34 @@
import com.taptap.ratelimiter.configuration.RateLimiterProperties;
import com.taptap.ratelimiter.exception.RateLimitException;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
* @author kl (http://kailing.pub)
* @since 2021/3/17
*/
@ControllerAdvice
@ConditionalOnProperty(prefix = RateLimiterProperties.PREFIX, name = "exceptionHandler.enable", havingValue = "true",matchIfMissing = true)
@ConditionalOnProperty(prefix = RateLimiterProperties.PREFIX, name = "exceptionHandler.enable", havingValue = "true", matchIfMissing = true)
public class RateLimitExceptionHandler {

private final RateLimiterProperties limiterProperties;
private final RateLimiterProperties limiterProperties;

public RateLimitExceptionHandler(RateLimiterProperties limiterProperties) {
this.limiterProperties = limiterProperties;
}

@ExceptionHandler(value = RateLimitException.class)
@ResponseBody
public String exceptionHandler(HttpServletResponse response, RateLimitException e){
response.setStatus(limiterProperties.getStatusCode());
response.setHeader("Retry-After", String.valueOf(e.getRetryAfter()));
return limiterProperties.getResponseBody();
public ResponseEntity<String> exceptionHandler(RateLimitException e) {

return ResponseEntity.status(limiterProperties.getStatusCode())
.header(HttpHeaders.RETRY_AFTER, String.valueOf(e.getRetryAfter()))
.contentType(MediaType.APPLICATION_JSON)
.body(limiterProperties.getResponseBody());
}
}

0 comments on commit 7b0dde4

Please sign in to comment.