New file |
| | |
| | | package com.ycl.config; |
| | | |
| | | import com.ycl.api.CommonResult; |
| | | import com.ycl.enums.common.ResultCode; |
| | | import com.ycl.exception.ApiException; |
| | | import org.springframework.context.annotation.Configuration; |
| | | import org.springframework.http.HttpStatus; |
| | | import org.springframework.stereotype.Controller; |
| | | import org.springframework.validation.FieldError; |
| | | import org.springframework.web.bind.MethodArgumentNotValidException; |
| | | import org.springframework.web.bind.annotation.*; |
| | | |
| | | import javax.servlet.http.HttpServletRequest; |
| | | |
| | | @Configuration |
| | | @ControllerAdvice(annotations = {RestController.class, Controller.class}) |
| | | @ResponseBody |
| | | public class ExceptionConfiguration { |
| | | // 捕获自定义异常数据 |
| | | @ExceptionHandler(value = ApiException.class) |
| | | public CommonResult HandlePubException(ApiException pubExceptions) { |
| | | System.out.println(String.format("错误:%d: %s", |
| | | pubExceptions.getErrorCode().getCode(), |
| | | pubExceptions.getErrorCode().getMessage())); |
| | | return CommonResult.failed(pubExceptions.getErrorCode()); |
| | | } |
| | | |
| | | @ExceptionHandler(value = MethodArgumentNotValidException.class) |
| | | public CommonResult HandleParamsException(HttpServletRequest request, MethodArgumentNotValidException exception) { |
| | | StringBuffer buffer = new StringBuffer(); |
| | | for (FieldError error : exception.getBindingResult().getFieldErrors()) { |
| | | buffer.append(String.format("参数:%s,值为:%s, 原因:%s。", error.getField(), error.getRejectedValue(), error.getDefaultMessage())); |
| | | } |
| | | return CommonResult.failed(ResultCode.VALIDATE_FAILED, buffer.toString()); |
| | | } |
| | | |
| | | // 捕获其他异常 |
| | | @ExceptionHandler// 直接返回500 |
| | | public CommonResult HandleAllException(Exception exception) { |
| | | |
| | | |
| | | exception.printStackTrace(); |
| | | // todo 记录日志 |
| | | |
| | | return CommonResult.failed(ResultCode.FAILED, "系统错误"); |
| | | } |
| | | |
| | | } |