1. 程式人生 > 其它 >全域性異常捕獲(支出@Valid)

全域性異常捕獲(支出@Valid)

package com.test3.handler;

import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver; import org.springframework.validation.BindException; import org.springframework.web.bind.MethodArgumentNotValidException; import com.test3.utils.JsonResult;
import com.test3.utils.MsgEnum; import com.test3.utils.MyException; /** * 異常捕獲rest處理 */ @ControllerAdvice public class ExceptionHandler extends ExceptionHandlerExceptionResolver{ private static final Logger logger = LoggerFactory.getLogger(ExceptionHandler.class); public static final String DEFAULT_ERROR_VIEW = "error"; @SuppressWarnings(
"unchecked") @org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class) @ResponseBody public JsonResult<Object> handle(Exception e) { e.printStackTrace(); if (e instanceof MyException) { MyException mye = (MyException) e; return JsonResult.errorResult(mye.getCode(), mye.getMessage()); } else if(e instanceof BindException) { // 非@RequestBody引數 BindException ex = (BindException)e; String msg = ex.getBindingResult().getAllErrors().stream() .filter(FieldError.class::isInstance) .map(FieldError.class::cast) .map(FieldError::getDefaultMessage) .collect(Collectors.joining()); return JsonResult.errorResult(5, msg); } else if (e instanceof MethodArgumentNotValidException) { //@RequestBody 引數 MethodArgumentNotValidException ex = (MethodArgumentNotValidException)e; String msg = ex.getBindingResult().getAllErrors().stream() .filter(FieldError.class::isInstance) .map(FieldError.class::cast) .map(FieldError::getDefaultMessage) .collect(Collectors.joining()); return JsonResult.errorResult(6, msg); }else { logger.error("未知異常:", e); if (e.getMessage() != null && e.getMessage().startsWith("Failed to convert value of type")) { return JsonResult.errorResult(MsgEnum.PARAMTYPE_ERROR); } else { return JsonResult.errorResult(MsgEnum.UNKNOW_ERROR); } } } //這裡是異常頁面跳轉,一般不使用, 注意需要加@org.springframework.web.bind.annotation.ExceptionHandler(value = Exception.class) 才能用 public ModelAndView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject("exception", e); mav.addObject("url", req.getRequestURL()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav; } }

1.加上@Valid

public JsonResult mytestnormal(@RequestBody @Valid TestRequest tq)

2.TestRequest.java中加上驗證註解

@NotBlank(message="標題不能為空!")
private String title;

無聊我就學英語