springboot 服务异常处理

    技术2025-04-17  12

    PS:sts快速查看类:ctrl + shift + T

    服务异常处理 (1)默认处理:BasicErrorController类 若以上请求头accept参数包含text/html,出错则走以下方法

    @RequestMapping(produces = "text/html") public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) { HttpStatus status = getStatus(request); Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes( request, isIncludeStackTrace(request, MediaType.TEXT_HTML))); response.setStatus(status.value()); ModelAndView modelAndView = resolveErrorView(request, response, status, model); return (modelAndView == null ? new ModelAndView("error", model) : modelAndView); }

    返回结果为html页面

    若以上请求头accept参数不包含text/html,出错则走以下方法

    @RequestMapping @ResponseBody public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { Map<String, Object> body = getErrorAttributes(request, isIncludeStackTrace(request, MediaType.ALL)); HttpStatus status = getStatus(request); return new ResponseEntity<Map<String, Object>>(body, status); }

    返回结果为json (2)springboot @valid 处理,进入control层,未调用服务层是校验报错:返回json并提示字段错误信息 (3)springboot 自定义报错处理: 采用RestControllerAdvice注解,全局处理control层抛出的异常

    package com.mall.pro.common.config; import com.mall.pro.common.exception.CommonBindException; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.validation.BindException; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; /** * 自定义错误处理器 * @author LGH */ @Controller @RestControllerAdvice public class DefaultExceptionHandlerConfig { @ExceptionHandler(BindException.class) public ResponseEntity<String> bindExceptionHandler(BindException e){ e.printStackTrace(); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getBindingResult().getFieldErrors().get(0).getDefaultMessage()); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){ e.printStackTrace(); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getBindingResult().getFieldErrors().get(0).getDefaultMessage()); } @ExceptionHandler(CommonBindException.class) public ResponseEntity<String> unauthorizedExceptionHandler(CommonBindException e){ e.printStackTrace(); return ResponseEntity.status(e.getHttpStatusCode()).body(e.getMessage()); } }
    Processed: 0.013, SQL: 9