4 months ago

Spring 中使用 @Valid 驗證後回覆的格式並不是 json ,其實很不好處理 ,目前是 定義 ControllerAdvice 來做一個轉換處理

還有另一個是 HystrixBadRequestException ,因為有用到 spring-cloud-feign 的功能,自然是支援斷路保護機制 但是這個HystrixBadRequestException 好像沒辦法把對方的錯誤訊息放進去我們的回覆資料內,對方只會看到 message=BadRequest 之類的,所以做一下處理

import com.netflix.hystrix.exception.HystrixBadRequestException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by samchu on 2017/4/13.
 */
@Slf4j
@ControllerAdvice
public class ExceptionHandlingController {

    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HystrixBadRequestException.class)
    public Map hystrixBadRequest(HttpServletRequest req, HystrixBadRequestException ex) {
        log.warn("HystrixBadRequestException = {}", ex);
        Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
        errorAttributes.put("timestamp", new Date());
        errorAttributes.put("status", 400);
        errorAttributes.put("error", "BadRequest");
        errorAttributes.put("exception", ex.getClass());
        errorAttributes.put("message", ex.getMessage());
        errorAttributes.put("path", req.getRequestURI());
        return errorAttributes;
    }

    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Map methodArgumentNotValid(HttpServletRequest req, MethodArgumentNotValidException ex) {
        Map<String, Object> errorAttributes = new LinkedHashMap<String, Object>();
        errorAttributes.put("timestamp", new Date());
        errorAttributes.put("status", 400);
        errorAttributes.put("error", "Validation failed");
        errorAttributes.put("exception", ex.getClass());
        List<ObjectError> objectErrorList = ex.getBindingResult().getAllErrors();
        StringBuilder sb = new StringBuilder();
        objectErrorList.forEach(error -> sb.append((sb.length() > 0 ? ", " : "") + error.getDefaultMessage()));
        errorAttributes.put("message", sb);
        errorAttributes.put("path", req.getRequestURI());
        return errorAttributes;
    }
}
← about use spring data Page Define entity resource link in spring data rest →
 
comments powered by Disqus